removeBg 之前一直使用的图片去背景工具
可以使用api集成其他平台,每月有50次免费调用次数
api 文档
文档中有nodejs示例,这里使用Nestjs改写了下

controller.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common';
import { OtherService } from './other.service';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('other')
export class OtherController {
constructor(private readonly other: OtherService) { }

@Post('removebg')
@UseInterceptors(FileInterceptor('file'))
async removeBg(@UploadedFile() file: Express.Multer.File) {
return await this.other.removeBg(file)
}
}

service.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { Injectable } from '@nestjs/common';
import axios from 'axios';
import { writeFileSync } from 'fs';
import { join } from 'path';

const FormData = require('form-data');

@Injectable()
export class OtherService {
// 调用 remove bg api 去除图片背景
private readonly RMBG_API_KEY = '自己的KEY'

async removeBg(file: Express.Multer.File) {
const { buffer, ext, fileName } = this.filterFile(file)

const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', buffer);

const { data, status, statusText } = await axios({
method: 'post',
url: 'https://api.remove.bg/v1.0/removebg',
data: formData,
responseType: 'arraybuffer',
headers: {
'X-Api-Key': this.RMBG_API_KEY,
},
})
if (status != 200) {
return {
success: false,
msg: statusText
}
}
// 将根目录下的public设置为了静态文件目录,所以将文件存储至public下的img下
const writeName = join(__dirname, '../../public/img/', fileName + "_no-bg.png")
writeFileSync(writeName, data);
return {
success: true,
msg: fileName + "_no-bg.png"
}
}
// 处理文件数据
filterFile(file: Express.Multer.File) {
// 二进制数据,原始文件名
const { buffer, originalname } = file
const extIndex = originalname.lastIndexOf(".")
const fileName = originalname.slice(0, extIndex);
// 后缀名
const ext = originalname.slice(extIndex + 1);

return {
buffer,
fileName,
ext
}
}
}