NestJs 使用removeBg api 实现图片去背景

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

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

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
        }
    }
}
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值