【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

比如不再支持默认导入。

相关推荐
MaisieKim_1 天前
python与nodejs哪个性能高
前端·python·node.js
水煮白菜王1 天前
深入理解 Webpack 核心机制与编译流程
前端·webpack·node.js
程序员拂雨1 天前
Express知识框架
node.js·express
大G哥1 天前
项目中利用webpack的require.context实现批量引入/导入图片
前端·webpack·node.js
七冬与小糖2 天前
【本地搭建npm私服】使用Verdaccio
前端·npm·node.js
巴巴_羊2 天前
webpack和vite区别
前端·webpack·node.js
亦世凡华、2 天前
前端npm包发布流程:从准备到上线的完整指南
前端·经验分享·npm·node.js·npm发包
X01动力装甲2 天前
Node.js 24.0 正式发布:性能跃升与开发体验全面升级
node.js
q567315232 天前
Node.js数据抓取技术实战示例
爬虫·python·scrapy·node.js
巴巴_羊2 天前
yarn npm pnpm
前端·npm·node.js