background-removal-js icon indicating copy to clipboard operation
background-removal-js copied to clipboard

Vanilla js deployment example

Open tal118 opened this issue 2 years ago • 3 comments

Novice here, apologies. Could an example be provided for deploying this with vanilla Javascript, from a web server that does not have any other node modules installed?

I'm struggling with the import statement and have tried various permutations with varying error results.

import imglyRemoveBackground from "@imgly/background-removal" -> 404 not found

import imglyRemoveBackground from "./@imgly/background-removal/dist/browser.js" -> Uncaught SyntaxError: The requested module './@imgly/background-removal/dist/browser.js' does not provide an export named 'imglyRemoveBackground'

I don't have experience with modules or packagers.

I'm hoping to use background-removal-js from within my Django based application.

tal118 avatar Aug 13 '23 11:08 tal118

I am looking for a more vanilla deployment as well so I can do this on a local.html page

Any help for this would be greatly appreciated.

jwcharp avatar Aug 17 '23 14:08 jwcharp

@jwcharp @tal118 Here is a quick&dirty example how to get it working.

The important thing being to import from browser.mjs and to import removeBackground instead of imglyRemoveBackground.

So create a file for example bg-remove.js:

import removeBackground from './node_modules/@imgly/background-removal/dist/browser.mjs';

function backgroundRemove(id) {
      const e = document.getElementById(id);
      const image_src = e.src;

      return removeBackground(image_src, {
              progress: (key, current, total) => {
                      console.log(`Processing (${key}: ${current} / ${total})...`;
              },
              debug: true,
              model: 'small'
      }).then((blob) => {
              // The result is a blob encoded as PNG. It can be converted to an URL to be used as HTMLImage.src
              e.src = URL.createObjectURL(blob);
      }).catch(function(err) {
              console.error('Could not process image', err);
      });
}

window.backgroundRemove = backgroundRemove;
export { backgroundRemove };

And source it from your HTML like this

<script type="module">
    import { backgroundRemove } from './bg-remove.js';

    backgroundRemove('someValidElementId');
</script>

Disclaimer: I'm also only a novice in Javascript, so this might be flawed a lot. Still it works...

lwindolf avatar Aug 29 '23 21:08 lwindolf

how can i do that in the current version? I tried it but is impossible for me.

addreeh avatar Jan 24 '24 10:01 addreeh