【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

比如不再支持默认导入。

相关推荐
脉动数据行情116 小时前
Node.js WebSocket 实现贵金属实时行情监听 伦敦金 / 伦敦银自动重连方案
websocket·node.js·vim
不老刘16 小时前
一行命令解决 Node.js 版本兼容问题:`--openssl-legacy-provider` 深度解析
node.js
万敏1 天前
Vue3 全栈实战:第一阶段复盘(第1-8周)
vue.js·node.js·全栈
濮水大叔1 天前
舒服了,CabloyJS 的 AI Spec 驱动开发会自动生成甘特图和燃尽图
typescript·node.js·vibecoding
FungLeo1 天前
成为全栈·Node 后端篇·部署上线:从本地起服到真正对外服务
node.js·后端部署·成为全栈
妙码生花2 天前
golang 应用服务端部署(使用 systemd 服务)
开发语言·人工智能·后端·golang·node.js·php·gin
柚稚姐姐2 天前
npm install pnpm -g npm error code EACCES npm error syscall symlink
前端·npm·node.js
FungLeo2 天前
成为全栈·Node 后端篇·容器化:给 Node 应用写一个像样的 Dockerfile
docker·node.js·dockerfile·成为全栈·后端服务容器·docker 容器
WeiXin_DZbishe3 天前
基于springboot大学生提问箱系统-计算机毕设【课程设计】72593
javascript·vue.js·spring boot·vscode·python·node.js·php
xixiaoyunya3 天前
Docker 容器化部署实战:从零搭建一套完整的 Nginx + Node.js + MySQL + Redis 项目环境
nginx·docker·node.js