【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

比如不再支持默认导入。

相关推荐
白菜__21 小时前
微信小程序网关逆向分析
javascript·微信小程序·小程序·node.js·网络爬虫·微信网关·小程序网关
Patrick_Wilson1 天前
IDE 升级重启后 Next.js dev 起不来?kill 无效的真正原因
node.js·next.js·前端工程化
小茴香3531 天前
大文件分片上传(前后端实现Vue+node.js)
前端·vue.js·node.js
liu_bees1 天前
nvm 极简教程:告别Node版本冲突!Windows下一键切换Node.js版本nvm安装与常用命令
windows·node.js·nvm
❀͜͡傀儡师1 天前
Aube:下一代 Node.js 包管理器,性能远超 pnpm
node.js·aube
海上彼尚2 天前
Nodejs也能写Agent - 3.基础篇 - Tools 与 Tool Calling
前端·人工智能·后端·node.js
qq_316837752 天前
npm run tauri build Downloading下载超时
前端·npm·node.js
光影少年2 天前
node开发生态
node.js·nestjs·掘金·金石计划
画画的阿飞2 天前
里程碑三:基于 Vue3 领域模型架构建设
前端·node.js
下北沢美食家2 天前
Webpack与Vite详解
前端·webpack·node.js