如何用Node.js为图片高效添加半透明水印?

2026-04-03 07:451阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1483个文字,预计阅读时间需要6分钟。

如何用Node.js为图片高效添加半透明水印?

如何利用Node.js给图片添加水印?

以下章节通过示例介绍如何使用Node.js为图片添加全屏半透明水印。

希望对大家有所帮助!

作为中后台项目的导出功能,经常会要求具备以下准备:

导出

怎么利用nodejs给图片添加水印?下面本篇文章通过示例来介绍一下使用node为图片添加全页面半透明水印的方法,希望对大家有所帮助!

作为中后台项目的导出功能,通常会被要求具备导出的追溯能力。

当导出的数据形态为图片时,一般会为图片添加水印以达到此目的。

DEMO

那么在导出图片前如何为其添加上可以作为导出者身份识别的水印呢?先看成品:

上图原图为我随便在网上找的一张图片,添加水印之后的效果如图所示。

业务需求分解

这里我们需要考虑在此业务场景之下,这个需求的三个要点:

  • 水印需要铺满整个图片
  • 水印文字成半透明状,保证原图的可读性
  • 水印文字应清晰可读

选型

如我一样负责在一个node.js server上实现以上需求,可选项相当多,比如直接使用c lib imagemagick或者已有人封装的各种node watermarking库。在本文中,我们将选择使用对Jimp库的封装。

Jimp 库的官方github页面上这样描述它自己:

An image processing library for Node written entirely in JavaScript, with zero native dependencies.

并且提供为数众多的操作图片的API

  • blit - Blit an image onto another.
  • blur - Quickly blur an image.
  • color - Various color manipulation methods.
  • contain - Contain an image within a height and width.
  • cover - Scale the image so the given width and height keeping the aspect ratio.
  • displace - Displaces the image based on a displacement map
  • dither - Apply a dither effect to an image.
  • flip - Flip an image along it's x or y axis.
  • gaussian - Hardcore blur.
  • invert - Invert an images colors
  • mask - Mask one image with another.
  • normalize - Normalize the colors in an image
  • print - Print text onto an image
  • resize - Resize an image.
  • rotate - Rotate an image.
  • scale - Uniformly scales the image by a factor.

在本文所述的业务场景中,我们只需使用其中部分API即可。

设计和实现

input 参数设计:

  • url: 原图片的存储地址(对于Jimp来说,可以是远程地址,也可以是本地地址)
  • textSize: 需添加的水印文字大小
  • opacity:透明度
  • text:需要添加的水印文字
  • dstPath:添加水印之后的输出图片地址,地址为脚本执行目录的相对路径
  • rotate:水印文字的旋转角度
  • colWidth:因为可旋转的水印文字是作为一张图片覆盖到原图上的,因此这里定义一下水印图片的宽度,默认为300像素
  • rowHeight:理由同上,水印图片的高度,默认为50像素。(PS:这里的水印图片尺寸可以大致理解为水印文字的间隔)

因此在该模块的coverTextWatermark函数中对外暴露以上参数即可

如何用Node.js为图片高效添加半透明水印?

coverTextWatermark

/** * @param {String} mainImage - Path of the image to be watermarked * @param {Object} options * @param {String} options.text - String to be watermarked * @param {Number} options.textSize - Text size ranging from 1 to 8 * @param {String} options.dstPath - Destination path where image is to be exported * @param {Number} options.rotate - Text rotate ranging from 1 to 360 * @param {Number} options.colWidth - Text watermark column width * @param {Number} options.rowHeight- Text watermark row height */ module.exports.coverTextWatermark = async (mainImage, options) => { try { options = checkOptions(options); const main = await Jimp.read(mainImage); const watermark = await textWatermark(options.text, options); const positionList = calculatePositionList(main, watermark) for (let i =0; i < positionList.length; i++) { const coords = positionList[i] main.composite(watermark, coords[0], coords[1] ); } main.quality(100).write(options.dstPath); return { destinationPath: options.dstPath, imageHeight: main.getHeight(), imageWidth: main.getWidth(), }; } catch (err) { throw err; } }

textWatermark

Jimp不能直接将文本旋转一定角度,并写到原图片上,因此我们需要根据水印文本生成新的图片二进制流,并将其旋转。最终以这个新生成的图片作为真正的水印添加到原图片上。下面是生成水印图片的函数定义:

const textWatermark = async (text, options) => { const image = await new Jimp(options.colWidth, options.rowHeight, '#FFFFFF00'); const font = await Jimp.loadFont(SizeEnum[options.textSize]) image.print(font, 10, 0, { text, alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE }, 400, 50) image.opacity(options.opacity); image.scale(3) image.rotate( options.rotation ) image.scale(0.3) return image }

calculatePositionList

到目前为止原图有了,水印图片也有了,如果想达到铺满原图的水印效果,我们还需要计算出水印图片应该在哪些坐标上画在原图上,才能达成水印铺满原图的目的。

const calculatePositionList = (mainImage, watermarkImg) => { const width = mainImage.getWidth() const height = mainImage.getHeight() const stepWidth = watermarkImg.getWidth() const stepHeight = watermarkImg.getHeight() let ret = [] for(let i=0; i < width; i=i+stepWidth) { for (let j = 0; j < height; j=j+stepHeight) { ret.push([i, j]) } } return ret }

如上代码所示,我们使用一个二维数组记录所有水印图片需出现在原图上的坐标列表。

总结

至此,关于使用Jimp为图片添加文字水印的所有主要功能就都讲解到了。

github地址:github.com/swearer23/jimp-fullpage-watermark

npm:npm i jimp-fullpage-watermark

Inspiration 致谢

github.com/sushantpaudel/jimp-watermark

github.com/luthraG/image-watermark

medium.com/@rossbulat/image-processing-in-nodejs-with-jimp-174f39336153

示例代码:

var watermark = require('jimp-fullpage-watermark'); watermark.coverTextWatermark('./img/main.jpg', { textSize: 5, opacity: 0.5, rotation: 45, text: 'watermark test', colWidth: 300, rowHeight: 50 }).then(data => { console.log(data); }).catch(err => { console.log(err); });

更多node相关知识,请访问:nodejs 教程!

以上就是浅析利用nodejs怎么给图片添加半透明水印(方法详解)的详细内容,更多请关注自由互联其它相关文章!

本文共计1483个文字,预计阅读时间需要6分钟。

如何用Node.js为图片高效添加半透明水印?

如何利用Node.js给图片添加水印?

以下章节通过示例介绍如何使用Node.js为图片添加全屏半透明水印。

希望对大家有所帮助!

作为中后台项目的导出功能,经常会要求具备以下准备:

导出

怎么利用nodejs给图片添加水印?下面本篇文章通过示例来介绍一下使用node为图片添加全页面半透明水印的方法,希望对大家有所帮助!

作为中后台项目的导出功能,通常会被要求具备导出的追溯能力。

当导出的数据形态为图片时,一般会为图片添加水印以达到此目的。

DEMO

那么在导出图片前如何为其添加上可以作为导出者身份识别的水印呢?先看成品:

上图原图为我随便在网上找的一张图片,添加水印之后的效果如图所示。

业务需求分解

这里我们需要考虑在此业务场景之下,这个需求的三个要点:

  • 水印需要铺满整个图片
  • 水印文字成半透明状,保证原图的可读性
  • 水印文字应清晰可读

选型

如我一样负责在一个node.js server上实现以上需求,可选项相当多,比如直接使用c lib imagemagick或者已有人封装的各种node watermarking库。在本文中,我们将选择使用对Jimp库的封装。

Jimp 库的官方github页面上这样描述它自己:

An image processing library for Node written entirely in JavaScript, with zero native dependencies.

并且提供为数众多的操作图片的API

  • blit - Blit an image onto another.
  • blur - Quickly blur an image.
  • color - Various color manipulation methods.
  • contain - Contain an image within a height and width.
  • cover - Scale the image so the given width and height keeping the aspect ratio.
  • displace - Displaces the image based on a displacement map
  • dither - Apply a dither effect to an image.
  • flip - Flip an image along it's x or y axis.
  • gaussian - Hardcore blur.
  • invert - Invert an images colors
  • mask - Mask one image with another.
  • normalize - Normalize the colors in an image
  • print - Print text onto an image
  • resize - Resize an image.
  • rotate - Rotate an image.
  • scale - Uniformly scales the image by a factor.

在本文所述的业务场景中,我们只需使用其中部分API即可。

设计和实现

input 参数设计:

  • url: 原图片的存储地址(对于Jimp来说,可以是远程地址,也可以是本地地址)
  • textSize: 需添加的水印文字大小
  • opacity:透明度
  • text:需要添加的水印文字
  • dstPath:添加水印之后的输出图片地址,地址为脚本执行目录的相对路径
  • rotate:水印文字的旋转角度
  • colWidth:因为可旋转的水印文字是作为一张图片覆盖到原图上的,因此这里定义一下水印图片的宽度,默认为300像素
  • rowHeight:理由同上,水印图片的高度,默认为50像素。(PS:这里的水印图片尺寸可以大致理解为水印文字的间隔)

因此在该模块的coverTextWatermark函数中对外暴露以上参数即可

如何用Node.js为图片高效添加半透明水印?

coverTextWatermark

/** * @param {String} mainImage - Path of the image to be watermarked * @param {Object} options * @param {String} options.text - String to be watermarked * @param {Number} options.textSize - Text size ranging from 1 to 8 * @param {String} options.dstPath - Destination path where image is to be exported * @param {Number} options.rotate - Text rotate ranging from 1 to 360 * @param {Number} options.colWidth - Text watermark column width * @param {Number} options.rowHeight- Text watermark row height */ module.exports.coverTextWatermark = async (mainImage, options) => { try { options = checkOptions(options); const main = await Jimp.read(mainImage); const watermark = await textWatermark(options.text, options); const positionList = calculatePositionList(main, watermark) for (let i =0; i < positionList.length; i++) { const coords = positionList[i] main.composite(watermark, coords[0], coords[1] ); } main.quality(100).write(options.dstPath); return { destinationPath: options.dstPath, imageHeight: main.getHeight(), imageWidth: main.getWidth(), }; } catch (err) { throw err; } }

textWatermark

Jimp不能直接将文本旋转一定角度,并写到原图片上,因此我们需要根据水印文本生成新的图片二进制流,并将其旋转。最终以这个新生成的图片作为真正的水印添加到原图片上。下面是生成水印图片的函数定义:

const textWatermark = async (text, options) => { const image = await new Jimp(options.colWidth, options.rowHeight, '#FFFFFF00'); const font = await Jimp.loadFont(SizeEnum[options.textSize]) image.print(font, 10, 0, { text, alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE }, 400, 50) image.opacity(options.opacity); image.scale(3) image.rotate( options.rotation ) image.scale(0.3) return image }

calculatePositionList

到目前为止原图有了,水印图片也有了,如果想达到铺满原图的水印效果,我们还需要计算出水印图片应该在哪些坐标上画在原图上,才能达成水印铺满原图的目的。

const calculatePositionList = (mainImage, watermarkImg) => { const width = mainImage.getWidth() const height = mainImage.getHeight() const stepWidth = watermarkImg.getWidth() const stepHeight = watermarkImg.getHeight() let ret = [] for(let i=0; i < width; i=i+stepWidth) { for (let j = 0; j < height; j=j+stepHeight) { ret.push([i, j]) } } return ret }

如上代码所示,我们使用一个二维数组记录所有水印图片需出现在原图上的坐标列表。

总结

至此,关于使用Jimp为图片添加文字水印的所有主要功能就都讲解到了。

github地址:github.com/swearer23/jimp-fullpage-watermark

npm:npm i jimp-fullpage-watermark

Inspiration 致谢

github.com/sushantpaudel/jimp-watermark

github.com/luthraG/image-watermark

medium.com/@rossbulat/image-processing-in-nodejs-with-jimp-174f39336153

示例代码:

var watermark = require('jimp-fullpage-watermark'); watermark.coverTextWatermark('./img/main.jpg', { textSize: 5, opacity: 0.5, rotation: 45, text: 'watermark test', colWidth: 300, rowHeight: 50 }).then(data => { console.log(data); }).catch(err => { console.log(err); });

更多node相关知识,请访问:nodejs 教程!

以上就是浅析利用nodejs怎么给图片添加半透明水印(方法详解)的详细内容,更多请关注自由互联其它相关文章!