【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

比如不再支持默认导入。

相关推荐
cz追天之路3 小时前
华为机考 ------ 识别有效的IP地址和掩码并进行分类统计
javascript·华为·typescript·node.js·ecmascript·less·css3
C_心欲无痕6 小时前
nodejs - npm run原理
前端·npm·node.js
千里马-horse7 小时前
TypedArrayOf
开发语言·javascript·c++·node.js·napi
程序员爱钓鱼8 小时前
Node.js 编程实战:错误处理与安全防护
前端·后端·node.js
程序员爱钓鱼8 小时前
Node.js 编程实战:模板引擎与静态资源
前端·后端·node.js
H@Z*rTE|i9 小时前
webpack 打包流程(极简记忆口诀)
前端·webpack·node.js
A_one20109 小时前
利用npm内置命令构建脚本工具
前端·npm·node.js
Summer不秃10 小时前
使用 SnapDOM + jsPDF 生成高质量 PDF (含多页分页, 附源码)
前端·javascript·vue.js·pdf·node.js
青衫折扇13 小时前
执行 npm 安装命令时,包被装到了 C 盘用户目录下,而非项目根目录
前端·npm·node.js
程序猿_极客13 小时前
【node期末作业开发】Node.js+MySQL 实现销售信息管理系统的增删改查(附源码)
数据库·mysql·node.js