【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

比如不再支持默认导入。

相关推荐
avoidaily5 小时前
使用Node.js分片上传大文件到阿里云OSS
阿里云·node.js·云计算
xd000025 小时前
8.axios Http网络请求库(1)
node.js
孟孟~5 小时前
npm run dev 报错:Error: error:0308010C:digital envelope routines::unsupported
前端·npm·node.js
孟孟~5 小时前
npm install 报错:npm error: ...node_modules\deasync npm error command failed
前端·npm·node.js
CUIYD_19899 小时前
Vue 中组件命名与引用
javascript·vue.js·node.js
全栈技术负责人9 小时前
Webpack性能优化:构建速度与体积优化策略
前端·webpack·node.js
程序猿小D14 小时前
第14节 Node.js 全局对象
linux·前端·npm·node.js·编辑器·vim
IT瘾君1 天前
JavaWeb:前端工程化-ElementPlus
前端·elementui·node.js·vue
早知道不学Java了1 天前
chromedriver 下载失败
前端·vue.js·react.js·npm·node.js
贩卖纯净水.1 天前
Webpack搭建本地服务器
前端·webpack·node.js