怎么利用nodejs給圖片添加水印?下面本篇文章通過示例來介紹一下使用node為圖片添加全頁面半透明水印的方法,希望對大家有所幫助!
DEMO
那么在導(dǎo)出圖片前如何為其添加上可以作為導(dǎo)出者身份識別的水印呢?先看成品:
業(yè)務(wù)需求分解
這里我們需要考慮在此業(yè)務(wù)場景之下,這個需求的三個要點:
- 水印需要鋪滿整個圖片
- 水印文字成半透明狀,保證原圖的可讀性
- 水印文字應(yīng)清晰可讀
選型
如我一樣負(fù)責(zé)在一個node.js server上實現(xiàn)以上需求,可選項相當(dāng)多,比如直接使用c lib imagemagick或者已有人封裝的各種node watermarking庫。在本文中,我們將選擇使用對Jimp庫的封裝。
Jimp 庫的官方github頁面上這樣描述它自己:
An image processing library for Node written entirely in JavaScript, with zero native dependencies.
并且提供為數(shù)眾多的操作圖片的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.
在本文所述的業(yè)務(wù)場景中,我們只需使用其中部分API即可。
設(shè)計和實現(xiàn)
input 參數(shù)設(shè)計:
- url: 原圖片的存儲地址(對于Jimp來說,可以是遠(yuǎn)程地址,也可以是本地地址)
- textSize: 需添加的水印文字大小
- opacity:透明度
- text:需要添加的水印文字
- dstPath:添加水印之后的輸出圖片地址,地址為腳本執(zhí)行目錄的相對路徑
- rotate:水印文字的旋轉(zhuǎn)角度
- colWidth:因為可旋轉(zhuǎn)的水印文字是作為一張圖片覆蓋到原圖上的,因此這里定義一下水印圖片的寬度,默認(rèn)為300像素
- rowHeight:理由同上,水印圖片的高度,默認(rèn)為50像素。(PS:這里的水印圖片尺寸可以大致理解為水印文字的間隔)
因此在該模塊的coverTextWatermark函數(shù)中對外暴露以上參數(shù)即可
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不能直接將文本旋轉(zhuǎn)一定角度,并寫到原圖片上,因此我們需要根據(jù)水印文本生成新的圖片二進制流,并將其旋轉(zhuǎn)。最終以這個新生成的圖片作為真正的水印添加到原圖片上。下面是生成水印圖片的函數(shù)定義:
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
到目前為止原圖有了,水印圖片也有了,如果想達到鋪滿原圖的水印效果,我們還需要計算出水印圖片應(yīng)該在哪些坐標(biāo)上畫在原圖上,才能達成水印鋪滿原圖的目的。
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 }
如上代碼所示,我們使用一個二維數(shù)組記錄所有水印圖片需出現(xiàn)在原圖上的坐標(biāo)列表。
總結(jié)
至此,關(guān)于使用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); });