業(yè)務(wù)背景
作為中后臺項目的導(dǎo)出功能赖淤,通常會被要求具備導(dǎo)出的追溯能力管搪。
當導(dǎo)出的數(shù)據(jù)形態(tài)為圖片時谆构,一般會為圖片添加水印以達到此目的裸扶。
DEMO
那么在導(dǎo)出圖片前如何為其添加上可以作為導(dǎo)出者身份識別的水印呢?先看成品:
上圖原圖為我隨便在網(wǎng)上找的一張圖片搬素,添加水印之后的效果如圖所示呵晨。
業(yè)務(wù)需求分解
這里我們需要考慮在此業(yè)務(wù)場景之下,這個需求的三個要點:
水印需要鋪滿整個圖片
水印文字成半透明狀蔗蹋,保證原圖的可讀性
水印文字應(yīng)清晰可讀
選型
如我一樣負責(zé)在一個nodejs server上實現(xiàn)以上需求何荚,可選項相當多,比如直接使用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來說,可以是遠程地址蜂筹,也可以是本地地址)
textSize: 需添加的水印文字大小
opacity:透明度
text:需要添加的水印文字
dstPath:添加水印之后的輸出圖片地址需纳,地址為腳本執(zhí)行目錄的相對路徑
rotate:水印文字的旋轉(zhuǎn)角度
colWidth:因為可旋轉(zhuǎn)的水印文字是作為一張圖片覆蓋到原圖上的,因此這里定義一下水印圖片的寬度艺挪,默認為300像素
rowHeight:理由同上不翩,水印圖片的高度,默認為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)該在哪些坐標上畫在原圖上,才能達成水印鋪滿原圖的目的寸五。
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)在原圖上的坐標列表。
總結(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
Image Processing in NodeJS with Jimp - Medium
示例代碼:
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);
});