💡 前端理解 -> 调用 Docker 工具
最近开始接触一个小东西,就是如何抠图 ✂️。需求是做一个「证件照」换背景 🎨,虽然这个很好做,PS 拾取颜色,一下子就搞定了。
但是,web 端可能也会有些用途 🌐。于是我就开始调研,如何实现这个功能 🔍。
最终,发现了 rembg 这个工具 🛠️,安装很简单,而且支持 Docker 部署 🐳,所以我就选择用 Docker 了。
做完之后发现,之前我还用过 pdf2htmlEX 📄➡️🌐 这个工具,可以用来转换 PDF 为 HTML,如果要使用,也是一样的思路。
🚀 实现
🎯 目标场景:
[用户上传证件照 🧑💼📸]
↓
[hono.js 后端接收请求 🌐✅]
↓
[调用 rembg docker 抠图 ✂️🐳✅]
↓
[前端处理换底色 🎨 / 裁剪 ✂️ / 压缩 🗜️✅]
这样实现很简单 ✅,前端只需要调个接口切图就行 🎯。然后换底色还是裁剪还是压缩,都是前端来处理 🧑💻。
不过后端遇到了一个问题 ⚠️,那就是 rembg 抠图是个耗时任务 🕐,如果并发处理太多,机器会爆 💥。
所以,后端这里我需要一个「轻量队列」🪶📋 来处理这个任务。
🔁 流程:
工作流程图:
1️⃣ 用户请求
2️⃣ -> Web 服务器 (生产者 🏭)
3️⃣ -> 将任务放入 Redis 队列 🧊📥
4️⃣ -> Worker (消费者 🧑🔧)
5️⃣ -> 从队列取出任务 📤
6️⃣ -> 调用 Docker 处理图片 🐳🖼️
7️⃣ -> 将结果缓存 🗂️
🧠 最终业务逻辑:
- 用户通过
/change-background接口发送图片 🖼️。 - 系统立即创建一个任务,并设置此任务的 Redis 记录在 5 分钟 后过期 ⏱️。然后返回
taskId🆔。 - Worker 拾取任务,在磁盘上创建临时文件 💾,调用
curl处理,然后从磁盘读取结果 📤。 - 任务完成后,Worker 触发
completed事件 ✅。 completed事件的监听器会创建一个带有 5 分钟延迟 的文件清理任务 🧹。- 用户在 5 分钟内可以通过
/status/:taskId接口查询结果 🔄。 - 5 分钟后:
- ⛔ BullMQ 会自动删除 Redis 中关于这个
taskId的所有记录。之后再查询/status/:taskId会返回404❌。 - ⏳
fileCleanupQueue中的延迟任务到期,fileCleanupWorker被触发,删除磁盘上对应的临时文件 🗑️。
- ⛔ BullMQ 会自动删除 Redis 中关于这个
🐳 1. 安装 Docker 镜像
# 拉取 rembg docker 镜像 ⬇️
docker pull --platform linux/amd64 danielgatis/rembg
# 运行 rembg docker 容器 ▶️
# docker run -d --name my-new-rembg -p 8080:8080 danielgatis/rembg
# 自定义包了一层 FastAPI 的镜像
docker run -d --name my-new-rembg -p 8080:8080 rembg-fastapi
# 运行 Redis 容器 🧊
docker run -d --name my-new-redis -p 6379:6379 redis:alpine
🧩 2. 开发后端逻辑
1️⃣ hono.js 如何调用 rembg 处理?
rembg Docker 镜像已经提供了 HTTP 接口 🌐,所以只需要调用这个接口就行 ✅。
2️⃣ 如何组织前后端处理图片的逻辑?
前端调用接口,后端处理图片 🔄。有了后端返回的处理状态,前端继续轮询,直到处理完成 🏁。
3️⃣ 如何实现「轻量队列」?
使用 BullMQ 和 Redis 实现 🛠️🧊。
4️⃣ 如何实现「文件清理」?
再新建一个队列 🧹,专门用来清理文件。避免代码耦合,让业务和资源清理分开 🪓。
5️⃣ 工具Docker没有提供 HTTP 接口
那我们需要在此基础上构建一个新的镜像,添加一个 HTTP 接口,比如通过 FastAPI 。
完整代码实现:
import { Hono } from 'hono'
import { z } from 'zod'
import { zValidator } from '@hono/zod-validator'
import { spawn } from 'child_process'
import fs from 'fs'
import path from 'path'
import { base64ToBuffer, bufferToBase64, getDateDir } from './utils'
import { Queue, Worker, Job } from 'bullmq'
import IORedis from 'ioredis'
// --- 常量定义 ---
const REMBG_API_URL = process.env.REMBG_API_URL || 'http://localhost:8000/api/remove'
const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379'
const CLEANUP_DELAY = 5 * 60 * 1000 // 5分钟,统一的清理延迟时间
// --- Redis 和 BullMQ 初始化 ---
const connection = new IORedis(REDIS_URL, {
maxRetriesPerRequest: null,
})
const removeBackgroundQueue = new Queue('removeBackground', { connection })
const fileCleanupQueue = new Queue('fileCleanup', { connection })
// --- Zod Schema (无变化) ---
const removeBackgroundSchema = z.object({
image: z.string(),
// 这两个字段在当前逻辑中没用到,但保留以备将来扩展
backgroundColor: z
.string()
.regex(/^#[0-9A-Fa-f]{6}$/)
.optional(),
tolerance: z.number().min(0).max(100).optional(),
})
// --- 核心处理函数 (修改版) ---
/**
* 将 Buffer 写入文件,调用外部服务处理,并返回输入和输出文件的路径。
* @param inputBuffer 图片的Buffer
* @returns 包含输入和输出文件路径的对象
*/
const removeBackgroundWithRembg = async (inputBuffer: Buffer): Promise<{ inputPath: string; outputPath: string }> => {
const baseDir = path.join(process.cwd(), 'storage', getDateDir())
await fs.promises.mkdir(baseDir, { recursive: true })
const timestamp = Date.now()
const inputPath = path.join(baseDir, `input-${timestamp}.png`)
const outputPath = path.join(baseDir, `output-${timestamp}.png`)
try {
await fs.promises.writeFile(inputPath, inputBuffer)
console.log('Saved input image to:', inputPath)
await new Promise<void>((resolve, reject) => {
const curl = spawn('curl', ['-X', 'POST', REMBG_API_URL, '-H', 'Content-Type: multipart/form-data', '-F', `file=@${inputPath}`, '--output', outputPath])
curl.on('error', reject)
curl.on('close', (code) => {
if (code === 0) resolve()
else reject(new Error(`curl exited with code ${code}`))
})
})
console.log('Processed image saved to:', outputPath)
return { inputPath, outputPath }
} catch (error) {
console.error('Rembg processing error:', error)
await fs.promises.unlink(inputPath).catch(() => {})
throw error
}
}
// --- BullMQ Workers ---
// 1. 主任务 Worker
const worker = new Worker(
'removeBackground',
async (job: Job) => {
const { imageB64 } = job.data
const imageBuffer = base64ToBuffer(imageB64)
// 这个函数现在只返回路径
const { inputPath, outputPath } = await removeBackgroundWithRembg(imageBuffer)
// 从输出文件读取结果,转换为 Base64,然后返回
const resultBuffer = await fs.promises.readFile(outputPath)
return {
image: bufferToBase64(resultBuffer, 'png'),
// 将路径也一并返回,供 'completed' 事件使用
inputPath,
outputPath,
}
},
{ connection, concurrency: 5 }
)
// 2. 文件清理 Worker (逻辑不变,非常重要)
const fileCleanupWorker = new Worker(
'fileCleanup',
async (job: Job) => {
const { inputPath, outputPath } = job.data
console.log(`[Cleanup Worker] Cleaning files: ${inputPath}, ${outputPath}`)
try {
await Promise.all([
fs.promises.unlink(inputPath).catch((err) => {
if (err.code !== 'ENOENT') throw err
}),
fs.promises.unlink(outputPath).catch((err) => {
if (err.code !== 'ENOENT') throw err
}),
])
console.log(`[Cleanup Worker] Successfully cleaned files for job ${job.id}`)
} catch (error) {
console.error(`[Cleanup Worker] Error cleaning files for job ${job.id}:`, error)
throw error
}
},
{ connection, concurrency: 10 }
)
// --- Worker 事件监听 ---
worker.on('completed', async (job, result) => {
console.log(`Job ${job.id} completed.`)
const { inputPath, outputPath } = result
// 添加一个5分钟后执行的文件清理任务
await fileCleanupQueue.add(
'cleanup-task',
{ inputPath, outputPath },
{
delay: CLEANUP_DELAY,
removeOnComplete: true, // 清理任务本身完成后立即删除
removeOnFail: true,
}
)
console.log(`Scheduled file cleanup for job ${job.id} in 5 minutes.`)
})
worker.on('failed', (job, err) => {
console.error(`Job ${job?.id} failed with error ${err.message}`)
// 失败任务的清理由 queue.add 中的 removeOnFail 配置自动处理
})
// --- Hono 路由 ---
const backgroundRoutes = new Hono()
backgroundRoutes.post('/change-background', zValidator('json', removeBackgroundSchema), async (c) => {
const { image } = c.req.valid('json')
// 每个请求都创建一个新任务,不再有缓存逻辑
const job = await removeBackgroundQueue.add(
'process-image',
{ imageB64: image },
{
// 关键:让 BullMQ 在任务完成后5分钟自动清理 Redis 中的记录
removeOnComplete: {
age: CLEANUP_DELAY / 1000, // age单位是秒
},
// 失败的任务也同样处理
removeOnFail: {
age: CLEANUP_DELAY / 1000,
},
}
)
return c.json({ taskId: job.id, status: 'queued' })
})
backgroundRoutes.get('/status/:taskId', async (c) => {
const taskId = c.req.param('taskId')
const job = await removeBackgroundQueue.getJob(taskId)
// 如果任务记录已经被清理,这里会返回 not_found,这是预期行为
if (!job) {
return c.json({ status: 'not_found_or_expired' }, 404)
}
const status = await job.getState()
if (status === 'completed') {
return c.json({
status,
image: job.returnvalue.image,
})
}
return c.json({ status })
})
export { backgroundRoutes }