In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is a detailed introduction to "how to add translucent watermark to pictures with nodejs". The content is detailed, the steps are clear, and the details are properly handled. I hope this article "how to add translucent watermark to pictures with nodejs" can help you solve your doubts. Let's go deeper and learn new knowledge together with the ideas of Xiaobian.
As an export function for background projects, traceability for export is usually required.
When the exported data is in the form of images, watermarks are usually added to the images to achieve this purpose.
DEMO
So how do you add a watermark that can be used as an identifier for the exporter before exporting the image? First look at the finished product:
The original picture above is a picture I found casually on the Internet. The effect after adding watermark is shown in the picture.
Business requirements decomposition
Here we need to consider three points of this requirement under this business scenario:
Watermarks need to cover the entire image
The watermark text is translucent to ensure the readability of the original image
Watermark text should be legible
selection
Like me, I am responsible for implementing the above requirements on a node.js server. There are quite a few options, such as using c lib imagemagick directly or various node watermarking libraries that have been encapsulated. In this article, we will choose to use encapsulation of the Jimp library.
Jimp's official github page describes itself as follows:
An image processing library for Node written entirely in JavaScript, with zero native dependencies.
And it provides a number of APIs for manipulating 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 scenario described in this article, we only need to use some of these APIs.
design and implementation
Input parameter design:
url: Store address of original image (remote address or local address for Jimp)
textSize: text size of watermark to be added
opacity: transparency
text: watermark text to be added
dstPath: the output image address after watermark is added, the address is the relative path of script execution directory
rotate: rotation angle of watermark text
colWidth: Because the rotatable watermark text is overlaid on the original image as an image, the width of the watermark image is defined here, and the default is 300 pixels.
rowHeight: For the same reason, the height of the watermark image, the default is 50 pixels. (PS: The watermark picture size here can be roughly understood as the interval of watermark text)
Therefore, the above parameters can be exposed to the outside in the coverTextWatermark function of the 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不能直接将文本旋转一定角度,并写到原图片上,因此我们需要根据水印文本生成新的图片二进制流,并将其旋转。最终以这个新生成的图片作为真正的水印添加到原图片上。下面是生成水印图片的函数定义: 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
So far, the original image has been created, and the watermark image has also been created. If you want to achieve the watermark effect of the original image, we still need to calculate which coordinates the watermark image should be drawn on the original image in order to achieve the purpose of watermarking the original image.
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} 如上代码所示,我们使用一个二维数组记录所有水印图片需出现在原图上的坐标列表。 示例代码: 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);}); Read here, this article "How to use nodejs to add translucent watermark to images" article has been introduced, want to master the knowledge of this article also need to be used by yourself to understand, if you want to know more related content of the article, welcome to pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 205
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.