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

作为中后台项目的导出功能,通常会被要求具备导出的追溯能力。
当导出的数据形态为图片时,一般会为图片添加水印以达到此目的。
DEMO
那么在导出图片前如何为其添加上可以作为导出者身份识别的水印呢?先看成品:

上图原图为我随便在网上找的一张图片,添加水印之后的效果如图所示。
业务需求分解
这里我们需要考虑在此业务场景之下,这个需求的三个要点:
- 水印需要铺满整个图片
 - 水印文字成半透明状,保证原图的可读性
 - 水印文字应清晰可读
 
选型
如我一样负责在一个 server上实现以上需求,可选项相当多,比如直接使用c lib imagemagick或者已有人封装的各种node watermarking库。在本文中,我们将选择使用对库的封装。
Jimp 库的官方github页面上这样描述它自己:
An image processing library for Node written entirely in JavaScript, with zero native dependencies.
并且提供为数众多的操作图片的API
- – Blit an image onto another.
 - – Quickly blur an image.
 - – Various color manipulation methods.
 - – Contain an image within a height and width.
 - – Scale the image so the given width and height keeping the aspect ratio.
 - – Displaces the image based on a displacement map
 - – Apply a dither effect to an image.
 - – Flip an image along it’s x or y axis.
 - – Hardcore blur.
 - – Invert an images colors
 - – Mask one image with another.
 - – Normalize the colors in an image
 - – Print text onto an image
 - – Resize an image.
 - – Rotate an image.
 - – Uniformly scales the image by a factor.
 
在本文所述的业务场景中,我们只需使用其中部分API即可。
设计和实现
input 参数设计:
- url: 原图片的存储地址(对于Jimp来说,可以是远程地址,也可以是本地地址)
 - textSize: 需添加的水印文字大小
 - opacity:透明度
 - text:需要添加的水印文字
 - dstPath:添加水印之后的输出图片地址,地址为脚本执行目录的相对路径
 - rotate:水印文字的旋转角度
 - colWidth:因为可旋转的水印文字是作为一张图片覆盖到原图上的,因此这里定义一下水印图片的宽度,默认为300像素
 - rowHeight:理由同上,水印图片的高度,默认为50像素。(PS:这里的水印图片尺寸可以大致理解为水印文字的间隔)
 
因此在该模块的coverTextWatermark函数中对外暴露以上参数即可
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地址:https://github.com/swearer23/jimp-fullpage-watermark
npm:npm i jimp-fullpage-watermark
Inspiration 致谢
https://github.com/sushantpaudel/jimp-watermark
https://github.com/luthraG/image-watermark
https://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怎么给图片添加半透明水印(方法详解)的详细内容,更多请关注php中文网其它相关文章!
声明:本文转载于:掘金社区,如有侵犯,请联系admin@php.cn删除
- 上一篇:
 - 下一篇:
 
2. 本站不保证所提供所有下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理,有奖励!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
4. 如果您也有好的资源或教程,您可以投稿发布,成功分享后有RB奖励和额外RMB收入!
磊宇堂正在使用的服务器 维护管理由磊宇云服务器提供支持
磊宇堂 » 浅析利用nodejs怎么给图片添加半透明水印(方法详解)
        
		