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.49k stars 339 forks source link

Cannot make it work with Vuejs #128

Open txstc55 opened 2 weeks ago

txstc55 commented 2 weeks ago

Tried to implement a simple background removal in vuejs:

<template>
  <div class="w-full h-full">
    <canvas ref="canvas"></canvas>
    <button @click="uploadImage">Upload Image</button>
    <input
      type="file"
      ref="fileInput"
      @change="handleFileChange"
      style="display: none"
      accept="image/*"
    />
  </div>
</template>
<script>
import removeBackground from '@imgly/background-removal';

export default {
  name: "TextCanvas",
  methods: {
    uploadImage() {
      this.$refs.fileInput.click();
    },
    async handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        const imageUrl = URL.createObjectURL(file);
        await this.processImage(imageUrl);
      }
    },
    async processImage(imageUrl) {
      const image = new Image();
      image.src = imageUrl;
      image.onload = async () => {
        const canvas = this.$refs.canvas;
        const ctx = canvas.getContext("2d");
        canvas.width = image.width;
        canvas.height = image.height;
        ctx.drawImage(image, 0, 0);

        await this.removeImageBackground();
      };
    },
    async removeImageBackground() {
      const canvas = this.$refs.canvas;
      const ctx = this.$refs.canvas.getContext('2d');
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      removeBackground(imageData).then((blob) => {
        // The result is a blob encoded as PNG. It can be converted to an URL to be used as HTMLImage.src
        const url = URL.createObjectURL(blob);
        console.log(url);
      })
    },
  },
  mounted() {
  },
};
</script>

However I kept getting error: (0 , _imgly_background_removalWEBPACK_IMPORTED_MODULE_0__.default) is not a function TypeError: (0 , _imgly_background_removalWEBPACK_IMPORTED_MODULE_0__.default) is not a function at Proxy.removeImageBackground (webpack-internal:///./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/components/TextCanvas.vue?vue&type=script&lang=js:38:76) at image.onload (webpack-internal:///./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/components/TextCanvas.vue?vue&type=script&lang=js:30:20)

I also tried to replace the call to imglyRemoveBackground according to https://www.npmjs.com/package/@imgly/background-removal I'm not sure why and I haven't seen any vuejs example with this package.