background-removeal-js去除图片背景

1,587 阅读1分钟

background-removeal-js是使用javascript语言写的一个用于去除图片背景的工具,可用于浏览器或nodejs环境中。

搭建环境

使用熟悉的前端框架创建一个项目,在这里使用vite+vue3+ant-design-vue

// 安装依赖
pnpm i @imgly/background-removal

使用

  1. @imgly/background-removal中导入removeBackgroundConfig
  2. Config用于配置去除背景时的一些参数,从仓库的/packages/web/README.md中可以查看在浏览器中使用的一些配置项。同理在node文件夹下可以查看nodejs环境中的使用方法。
  3. 转换后的文件是blob格式,在这里我们使用blob转base64格式在浏览器中预览。
  4. 该库使用的模型文件默认存储在线上,可以根据安装的background-removeal-js版本在https://staticimgly.com/@imgly/background-removal-data/包的版本号(如1.5.5)/package.tgz下载对应的模型文件。下载后的模型文件可以存放在自己的资源服务器中。为了简便,我在这里放到了public文件夹下

代码:

<script setup lang="ts">
import { ref } from 'vue'
import { Button, Upload } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue';
import { removeBackground, Config } from "@imgly/background-removal"

const fileList = ref([])
const beforeSrc = ref('')
const afterSrc = ref('')

const headers = {
  authorization: 'authorization-text',
}
// 模型文件访问路径
const public_path = "http://localhost:5173/package/dist/"
let config: Config = {
  publicPath: public_path
};

const customRequest = (info: any) => {
  fileToBase64(info.file)
  removeBackground(info.file, config).then(res => {
    console.log(res)
    blobToDataURI(res, (result: any) => {
      afterSrc.value = result
    })
  })
}

// file 转base 64
function fileToBase64(file: any) {
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    beforeSrc.value = reader.result as string;
  }
  reader.onerror = function (err) {
    console.log(err);
  }
}

// blob 转 base64
function blobToDataURI(blob: any, callback: any) {
  var reader = new FileReader();
  reader.readAsDataURL(blob);
  reader.onload = function (e) {
    callback(e.target!.result);
  };
}


</script>

<template>
    <div>
      <Upload 
        v-model:file-list="fileList" 
        name="file" 
        :customRequest="customRequest" 
        :headers="headers">
        <Button>
          <upload-outlined></upload-outlined>
          上传图片
        </Button>
      </Upload>
    </div>
    <div style="display: flex; justify-content: center;">
        <img style='width: 400px' :src="beforeSrc">
        <img style='width: 400px' :src="afterSrc">
    </div>
</template>

效果图

Snipaste_2024-08-25_15-12-18.png

完结撒花