imgly / background-removal-js

Remove backgrounds from images directly in the browser environment with ease and no additional costs or privacy concerns. Explore an interactive demo.
https://img.ly/showcases/cesdk/web/background-removal/web
GNU Affero General Public License v3.0
5.7k stars 357 forks source link

Vanilla js deployment example #27

Open tal118 opened 1 year ago

tal118 commented 1 year ago

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.

jwcharp commented 1 year ago

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.

lwindolf commented 1 year ago

@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...

addreeh commented 8 months ago

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