Home  >  Article  >  Web Front-end  >  A brief analysis of how to add translucent watermarks to images using nodejs (detailed explanation of the method)

A brief analysis of how to add translucent watermarks to images using nodejs (detailed explanation of the method)

青灯夜游
青灯夜游forward
2022-02-22 19:38:563378browse

How to add watermark to images using nodejs? The following article uses an example to introduce how to use node to add a full-page translucent watermark to an image. I hope it will be helpful to everyone!

A brief analysis of how to add translucent watermarks to images using nodejs (detailed explanation of the method)

#As the export function of mid- and back-end projects, we are usually required to have export traceability capabilities.

When the exported data is in the form of pictures, watermarks are generally added to the pictures to achieve this purpose.

DEMO

So how do you add a watermark that can be used as the exporter’s identity before exporting a picture? Let’s take a look at the finished product first:

A brief analysis of how to add translucent watermarks to images using nodejs (detailed explanation of the method)

#The original picture above is a picture I randomly found online. The effect after adding the watermark is as shown in the picture.

Business requirement decomposition

Here we need to consider three key points of this requirement under this business scenario:

  • The watermark needs to cover the entire image
  • The watermark text should be translucent to ensure the readability of the original image
  • The watermark text should be clear and readable

Selection

As I am responsible for implementing the above requirements on a node.js server, there are quite a few options, such as using it directly c lib imagemagick or various node watermarking libraries that have been packaged by others. In this article, we will choose to use the package of the Jimp library.

The official github page of the Jimp library describes itself like this:

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

And provides a large number of APIs for operating images

  • 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.

In the business described in this article In the scenario, we only need to use some of the APIs.

Design and implementation

Input parameter design:

  • url: The storage address of the original image (for Jimp For example, it can be a remote address or a local address)
  • textSize: The size of the watermark text that needs to be added
  • opacity: Transparency
  • text: The watermark text that needs to be added
  • dstPath: The output image address after adding the watermark, the address is the relative path of the script execution directory
  • rotate: The rotation angle of the watermark text
  • colWidth: Because the watermark can be rotated The text is overlaid on the original image as an image, so define the width of the watermark image here, the default is 300 pixels
  • rowHeight: The reason is the same as above, the height of the watermark image is 50 pixels by default. (PS: The size of the watermark image here can be roughly understood as the interval of the watermark text)

Therefore, the above parameters can be exposed to the outside in the coverTextWatermark function of this module

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 cannot directly rotate the text to a certain angle and write it to the original image, so we need to generate a new image binary based on the watermark text stream and rotate it. Finally, this newly generated image is added to the original image as a real watermark. The following is the function definition for generating watermark images:

const textWatermark = async (text, options) => {
  const image = await new Jimp(options.colWidth, options.rowHeight, &#39;#FFFFFF00&#39;);
  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(&#39;jimp-fullpage-watermark&#39;);

watermark.coverTextWatermark(&#39;./img/main.jpg&#39;, {
  textSize: 5,
  opacity: 0.5,
  rotation: 45,
  text: &#39;watermark test&#39;,
  colWidth: 300,
  rowHeight: 50
}).then(data => {
    console.log(data);
}).catch(err => {
    console.log(err);
});

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

The above is the detailed content of A brief analysis of how to add translucent watermarks to images using nodejs (detailed explanation of the method). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete