【Node.js】图片水印

  1. 上传时加水印
    用户上传原始图片->服务器:保留原始图片以及水印图片
  2. 动态水印
    用户上传原始图片->服务器:只保留原始图片
    请求图片时,服务器动态加水印

根据业务需求自行更改操作,下面只讲最简单的给图片加水印。

主要使用到了库为 jimp

js 复制代码
const path = require("path");
const {Jimp} = require('jimp');

// 给一张图片添加水印
async function addWatermark(waterFile, originFile, targetFile, proportion = 10, marginProportion = 0.05) {
    const [water, origin] = await Promise.all([
        Jimp.read(waterFile),
        Jimp.read(originFile)
    ])
    // 对水印图片进行缩放
    const curProportion = origin.bitmap.width / water.bitmap.width;
    water.scale(curProportion / proportion);
    // 计算位置
    const right = origin.bitmap.width * marginProportion;
    const bottom = origin.bitmap.height * marginProportion;
    const x = origin.bitmap.width - water.bitmap.width - right;
    const y = origin.bitmap.height - water.bitmap.height - bottom;
    // 写入水印
    origin.composite(water, x, y, {
        mode: Jimp.BLEND_SOURCE_OVER,
        opacitySource: 0.5
    });
    await origin.write(targetFile);
}

async function test() {
    const waterPath = path.resolve(__dirname, 'resource', 'water.png');
    const originPath = path.resolve(__dirname, 'resource', 'origin.png');
    const targetPath = path.resolve(__dirname, 'resource', 'target.png');
    await addWatermark(waterPath, originPath, targetPath);
}

test()

这里需要注意,我使用的 jimp 版本为 "jimp": "^1.6.0",该版本相对于 0 版本有一些改动,见 :migrate-to-v1

比如不再支持默认导入。

相关推荐
烂蜻蜓7 小时前
Node.js入门教程(三十一):Express 框架
node.js·express
小屁孩你滑稽掉了8 小时前
prisma操作数据库的方法使用教程(简洁版)
数据库·node.js·prisma·fastify
__zRainy__9 小时前
Node系列 · Node基础:https 模块
后端·网络协议·http·https·node.js
__zRainy__18 小时前
Node.js Web 框架选型指南:从 Express 到 Hono 的全景对比
前端·node.js·express·koa·nestjs·egg·fastify
烂蜻蜓18 小时前
Node.js入门教程(二十八):GET/POST请求
node.js
__zRainy__1 天前
Node系列 · Node基础:net 模块
后端·node.js
嘟嘟07171 天前
从浏览器到 hello world:Docker + nginx 反向代理 + Node 最小服务器一次讲清
docker·容器·node.js
FungLeo1 天前
Node 后端实战 · 老系统数据迁移怎么不出乱子?V1→V2 重构实战与 3 个生产坑
node.js·serverless·数据库迁移·d1 数据库
今日无bug1 天前
Tool Use 工具调用 —— 让LLM缸中大脑突破物理限制的3个阶段
node.js·llm·agent
To_OC2 天前
装完 ESLint 它一声不吭?我还以为代码写得多好
后端·node.js·eslint