【W(wǎng)eb技術(shù)】1348- 聊聊水印實(shí)現(xiàn)的幾種方式
遇到問(wèn)題
日常工作中,經(jīng)常會(huì)遇到很多敏感的數(shù)據(jù),為防止數(shù)據(jù)的泄露,我們要在數(shù)據(jù)上做一些”包裝“。目的就是讓那些有心泄露數(shù)據(jù)的”不法分子“迫于嚴(yán)重的”輿論壓力“而放棄不法行為,使之”犯罪未遂“,達(dá)到不戰(zhàn)而屈人之兵的效果。而在安全部門(mén)工作的我們,數(shù)據(jù)安全的觀念早已深入骨髓,每個(gè)文字,每張圖片,都要留心是否有泄露的風(fēng)險(xiǎn),怎么防止數(shù)據(jù)泄露,是我們一直思考的問(wèn)題。比如圖片的水印,就是我們工作過(guò)程中經(jīng)常涉及到的問(wèn)題。因?yàn)楸旧砉ぷ鲀?nèi)容就是審核平臺(tái)的開(kāi)發(fā),經(jīng)常有一些風(fēng)險(xiǎn)圖片會(huì)在審核平臺(tái)出現(xiàn),考慮到審核人員的安全意識(shí)參差不齊,所以為防止不安全的事情發(fā)生,圖片增加水印的工作是必須要做的。
分析問(wèn)題
首先,考慮到業(yè)務(wù)場(chǎng)景,現(xiàn)階段的問(wèn)題只是在審核過(guò)程中擔(dān)心數(shù)據(jù)的泄露,我們暫時(shí)只考慮顯式水印,既在圖片上增加一些可以區(qū)別你個(gè)人身份的文字或者其他數(shù)據(jù)。這樣就可以做到根據(jù)泄露的數(shù)據(jù)可以追查到個(gè)人,當(dāng)然,未雨綢繆,防患于未然的警示功能才是它最主要。
解決問(wèn)題
實(shí)現(xiàn)方式
水印的實(shí)現(xiàn)方式有很多,根據(jù)實(shí)現(xiàn)功能的人員分工可以分為前端水印和后端水印,前端水印的優(yōu)點(diǎn)可以總結(jié)為三點(diǎn),第一,可以不占用服務(wù)器資源,完全依賴客戶端的計(jì)算能力,減少服務(wù)端壓力。第二,速度快,無(wú)論哪種前端的實(shí)現(xiàn)方式,性能都是優(yōu)于后端的。第三,實(shí)現(xiàn)方式簡(jiǎn)單。后端實(shí)現(xiàn)水印的最大優(yōu)勢(shì)也可以總結(jié)為三點(diǎn),就是安全,安全,安全。知乎,微博都是采用后端實(shí)現(xiàn)的水印方案。但是綜合考慮,我們還是采用前端實(shí)現(xiàn)水印的方案。下面也會(huì)簡(jiǎn)單介紹下 nodejs 怎么實(shí)現(xiàn)后端圖片水印。
node實(shí)現(xiàn)
提供三個(gè) npm 包,本部分不是我們文章的重點(diǎn),只提供簡(jiǎn)單的 demo。1,gm https://github.com/aheckmann/gm 6.4k star
const fs = require('fs');
const gm = require('gm');
gm('/path/to/my/img.jpg')
.drawText(30, 20, "GMagick!")
.write("/path/to/drawing.png", function (err) {
if (!err) console.log('done');
});
需要安裝 GraphicsMagick 或者 ImageMagick;2,node-images:https://github.com/zhangyuanwei/node-images
var images = require("images");
images("input.jpg") //Load image from file
//加載圖像文件
.size(400) //Geometric scaling the image to 400 pixels width
//等比縮放圖像到400像素寬
.draw(images("logo.png"), 10, 10) //Drawn logo at coordinates (10,10)
//在(10,10)處繪制Logo
.save("output.jpg", { //Save the image to a file, with the quality of 50
quality : 50 //保存圖片到文件,圖片質(zhì)量為50
});
不需要安裝其他工具,輕量級(jí),zhangyuanwei 國(guó)人開(kāi)發(fā),中文文檔;3,jimp:https://github.com/oliver-moran/jimp可搭配 gifwrap 實(shí)現(xiàn) gif 水印;
前端實(shí)現(xiàn)
1,背景圖實(shí)現(xiàn)全屏水印
可以到阿里內(nèi)外個(gè)人信息頁(yè)面查看效果,原理:

優(yōu)點(diǎn):圖片是后端生成,安全;缺點(diǎn):需要發(fā)起 http 請(qǐng)求,獲取圖片信息;效果展示:由于是內(nèi)部系統(tǒng),不方便展示效果。
2,dom 實(shí)現(xiàn)全圖水印和圖片水印
在圖片的 onload 事件里獲取圖片寬高,根據(jù)圖片大小生成水印區(qū)域,遮擋在圖片上層,dom 內(nèi)容為水印的文案或者其他信息,實(shí)現(xiàn)方式比較簡(jiǎn)單。
const wrap = document.querySelector('#ReactApp');
const { clientWidth, clientHeight } = wrap;
const waterHeight = 120;
const waterWidth = 180;
// 計(jì)算個(gè)數(shù)
const [columns, rows] = [~~(clientWidth / waterWidth), ~~(clientHeight / waterHeight)]
for (let i = 0; i < columns; i++) {
for (let j = 0; j <= rows; j++) {
const waterDom = document.createElement('div');
// 動(dòng)態(tài)設(shè)置偏移值
waterDom.setAttribute('style', `
width: ${waterWidth}px;
height: ${waterHeight}px;
left: ${waterWidth + (i - 1) * waterWidth + 10}px;
top: ${waterHeight + (j - 1) * waterHeight + 10}px;
color: #000;
position: absolute`
);
waterDom.innerText = '測(cè)試水印';
wrap.appendChild(waterDom);
}
}
優(yōu)點(diǎn):簡(jiǎn)單易實(shí)現(xiàn);缺點(diǎn):圖片過(guò)大或者過(guò)多會(huì)有性能影響;效果展示:

3,canvas 實(shí)現(xiàn)方式(第一版實(shí)現(xiàn)方案)方法一:直接在圖片上操作
廢話不多說(shuō),直接上代碼
useEffect(() => {
// gif 圖不支持
if (src && src.includes('.gif')) {
setShowImg(true);
}
image.onload = function () {
try {
// 太小的圖不加載水印
if (image.width < 10) {
setIsDataError(true);
props.setIsDataError && props.setIsDataError(true);
return;
}
const canvas = canvasRef.current;
canvas.width = image.width;
canvas.height = image.height;
// 設(shè)置水印
const font = `${Math.min(Math.max(Math.floor(innerCanvas.width / 14), 14), 48)}px` || fontSize;
innerContext.font = `${font} ${fontFamily}`;
innerContext.textBaseline = 'hanging';
innerContext.rotate(rotate * Math.PI / 180);
innerContext.lineWidth = lineWidth;
innerContext.strokeStyle = strokeStyle;
innerContext.strokeText(text, 0, innerCanvas.height / 4 * 3);
innerContext.fillStyle = fillStyle;
innerContext.fillText(text, 0, innerCanvas.height / 4 * 3);
const context = canvas.getContext('2d');
context.drawImage(this, 0, 0);
context.rect(0, 0, image.width || 200, image.height || 200);
// 設(shè)置水印浮層
const pattern = context.createPattern(innerCanvas, 'repeat');
context.fillStyle = pattern;
context.fill();
} catch (err) {
console.info(err);
setShowImg(true);
}
};
image.onerror = function () {
setShowImg(true);
};
}, [src]);
優(yōu)點(diǎn):純前端實(shí)現(xiàn)方式,右鍵復(fù)制的圖片也是有水印的;缺點(diǎn):不支持 gif,圖片必須支持跨域;效果展示:下文給出。
方法二:canvas 生成水印 url 賦值給 css background 屬性
export const getBase64Background = (props) => {
const { nick, empId } = GlobalConfig.userInfo;
const {
rotate = -20,
height = 75,
width = 85,
text = `${nick}-${empId}`,
fontSize = '14px',
lineWidth = 2,
fontFamily = 'microsoft yahei',
strokeStyle = 'rgba(255, 255, 255, .15)',
fillStyle = 'rgba(0, 0, 0, 0.15)',
position = { x: 30, y: 30 },
} = props;
const image = new Image();
image.crossOrigin = 'Anonymous';
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
context.font = `${fontSize} ${fontFamily}`;
context.lineWidth = lineWidth;
context.rotate(rotate * Math.PI / 180);
context.strokeStyle = strokeStyle;
context.fillStyle = fillStyle;
context.textAlign = 'center';
context.textBaseline = 'hanging';
context.strokeText(text, position.x, position.y);
context.fillText(text, position.x, position.y);
return canvas.toDataURL('image/png');
};
// 使用方式
<img src="https://xxx.xxx.jpg" />
<div className="warter-mark-area" style={{ backgroundImage: `url(${getBase64Background({})})` }} />
優(yōu)點(diǎn):純前端實(shí)現(xiàn)方式,支持跨域,支持 git 圖水印;缺點(diǎn):生成的 base64 url 比較大;效果展示:下文給出。其實(shí)根據(jù)這兩種 canvas 的實(shí)現(xiàn)方式可以輕松的想出第三種方式,就是在圖片的上層遮一層 第一方法中的非圖片的 canvas,這樣就能完美的避免兩種方案的缺點(diǎn)。但是停留片刻想一下,兩種方案的結(jié)合,還是使用 canvas 去繪制,是不是有更簡(jiǎn)單易懂的方式呢。對(duì),用 svg 替代。
4,SVG 方式(正在使用的方案)給出一個(gè) react 版的水印組件。
export const WaterMark = (props) => {
// 獲取水印數(shù)據(jù)
const { nick, empId } = GlobalConfig.userInfo;
const boxRef = React.createRef();
const [waterMarkStyle, setWaterMarkStyle] = useState('180px 120px');
const [isError, setIsError] = useState(false);
const {
src, text = `${nick}-${empId}`, height: propsHeight, showSrc, img, nick, empId
} = props;
// 設(shè)置背景圖和背景圖樣式
const boxStyle = {
backgroundSize: waterMarkStyle,
backgroundImage: `url("data:image/svg+xml;utf8,<svg width=\'100%\' height=\'100%\' xmlns=\'http://www.w3.org/2000/svg\' version=\'1.1\'><text width=\'100%\' height=\'100%\' x=\'20\' y=\'68\' transform=\'rotate(-20)\' fill=\'rgba(0, 0, 0, 0.2)\' font-size=\'14\' stroke=\'rgba(255, 255, 255, .2)\' stroke-width=\'1\'>${text}</text></svg>")`,
};
const onLoad = (e) => {
const dom = e.target;
const {
previousSibling, nextSibling, offsetLeft, offsetTop,
} = dom;
// 獲取圖片寬高
const { width, height } = getComputedStyle(dom);
if (parseInt(width.replace('px', '')) < 180) {
setWaterMarkStyle(`${width} ${height.replace('px', '') / 2}px`);
};
previousSibling.style.height = height;
previousSibling.style.width = width;
previousSibling.style.top = `${offsetTop}px`;
previousSibling.style.left = `${offsetLeft}px`;
// 加載 loading 隱藏
nextSibling.style.display = 'none';
};
const onError = (event) => {
setIsError(true);
};
return (
<div className={styles.water_mark_wrapper} ref={boxRef}>
<div className={styles.water_mark_box} style={boxStyle} />
{isError
? <ErrorSourceData src={src} showSrc={showSrc} height={propsHeight} text="圖片加載錯(cuò)誤" helpText="點(diǎn)擊復(fù)制圖片鏈接" />
: (
<>
<img onLoad={onLoad} referrerPolicy="no-referrer" onError={onError} src={src} alt="圖片顯示錯(cuò)誤" />
<Icon className={styles.img_loading} type="loading" />
</>
)
}
</div>
);
};
優(yōu)點(diǎn):支持 gif 圖水印,不存在跨域問(wèn)題,使用 repeat 屬性,無(wú)插入 dom 過(guò)程,無(wú)性能問(wèn)題;缺點(diǎn):。。。dom 結(jié)構(gòu)展示:

5,效果圖展示canvas 和 svg 實(shí)現(xiàn)的效果在展示上沒(méi)有很大的區(qū)別,所以效果圖就一張圖全部展示了。

QA
問(wèn)題一:
如果把 watermark 的 dom 刪除了,圖片不就是無(wú)水印了嗎?答案:可以利用 MutationObserver 監(jiān)聽(tīng) water 的節(jié)點(diǎn),如果節(jié)點(diǎn)被修改,圖片也隨之隱藏;
問(wèn)題二:
鼠標(biāo)右鍵復(fù)制圖片?答案:全部的圖片都禁用了右鍵功能
問(wèn)題三:
如果從控制臺(tái)的network獲取圖片信息呢?答案:此操作暫時(shí)沒(méi)有想到好的解決辦法,建議采用后端實(shí)現(xiàn)方案
總結(jié)
前端實(shí)現(xiàn)的水印方案始終只是一種臨時(shí)方案,業(yè)務(wù)后端實(shí)現(xiàn)又耗費(fèi)服務(wù)器資源,其實(shí)最理想的解決方式就是提供一個(gè)獨(dú)立的水印服務(wù),雖然加載過(guò)程中會(huì)略有延遲,但是相對(duì)與數(shù)據(jù)安全來(lái)說(shuō),毫秒級(jí)的延遲還是可以接受的,這樣又能保證不影響業(yè)務(wù)的服務(wù)穩(wěn)定性。在每天的答疑過(guò)程中,也會(huì)有很多業(yè)務(wù)方來(lái)找我溝通水印遮擋風(fēng)險(xiǎn)點(diǎn)的問(wèn)題,每次只能用數(shù)據(jù)安全的重要性來(lái)回復(fù)他們,當(dāng)然,水印的大小,透明度,密集程度也都在不斷的調(diào)優(yōu)中,相信會(huì)有一個(gè)版本,既能起到水印的作用,也能更好的解決遮擋問(wèn)題。
本文作者:ES2049 /卜露
本文鏈接:https://segmentfault.com/a/1190000040425430
