【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

比如不再支持默认导入。

相关推荐
YongGit33 分钟前
探索 AI + MCP 渲染前端 UI
前端·后端·node.js
ncj3934379063 小时前
vscode中对node项目进行断点调试
vscode·node.js
abigale035 小时前
webpack+vite前端构建工具 -11实战中的配置技巧
前端·webpack·node.js
墨菲安全15 小时前
NPM组件 betsson 等窃取主机敏感信息
前端·npm·node.js·软件供应链安全·主机信息窃取·npm组件投毒
csdn_aspnet1 天前
Node.js 使用 WebSockets 和 Socket.IO 实现实时聊天应用程序
node.js
whhhhhhhhhw1 天前
Node.js核心API(fs篇)
node.js
聪聪的学习笔记1 天前
【1】确认安装 Node.js 和 npm版本号
前端·npm·node.js
GDAL2 天前
Node.js v22.5+ 官方 SQLite 模块全解析:从入门到实战
数据库·sqlite·node.js
RunsenLIu2 天前
基于Vue.js + Node.js + MySQL实现的图书销售管理系统
vue.js·mysql·node.js
Allen_zx2 天前
Elpis - 基于 Koa + Vue3 的企业级全栈应用框架
node.js