【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

比如不再支持默认导入。

相关推荐
acaiEncode4 小时前
nvm use xxx 报错: exit status 145: The directory is not empty.
前端·node.js
程序员爱钓鱼5 小时前
Node.js 编程实战:自定义模块与包发布全流程解析
后端·node.js·trae
程序员爱钓鱼6 小时前
Node.js 编程实战:深入理解回调函数
后端·node.js·trae
```???6 小时前
666666999999
javascript·tcp/ip·node.js
孟祥_成都7 小时前
nest.js / hono.js 一起学!开发前必备!
前端·node.js
互联网全栈开发实战7 小时前
一款超优秀的数据可视化平台(大屏设计器【2025年 - 2026年】)-GoView(构建数字孪生可视化新世界)
信息可视化·数据分析·node.js·vue·数据可视化·大屏端
未知原色9 小时前
NODE.JSB快速下载及安装
linux·运维·node.js
我爱学习_zwj9 小时前
Node.js实战:打造随机文章生成器
node.js
我爱学习_zwj9 小时前
Node.js模块化入门指南
前端·node.js
Watermelo61710 小时前
如何优雅地导出 VS Code 项目目录结构
前端·javascript·vue.js·vscode·算法·性能优化·node.js