平常工做中,常常會遇到不少敏感的數據,爲防止數據的泄露,咱們要在數據上作一些」包裝「。目的就是讓那些有心泄露數據的」不法分子「迫於嚴重的」輿論壓力「而放棄不法行爲,使之」犯罪未遂「,達到不戰而屈人之兵的效果。而在安所有門工做的咱們,數據安全的觀念早已深刻骨髓,每一個文字,每張圖片,都要留心是否有泄露的風險,怎麼防止數據泄露,是咱們一直思考的問題。好比圖片的水印,就是咱們工做過程當中常常涉及到的問題。由於自己工做內容就是審覈平臺的開發,常常有一些風險圖片會在審覈平臺出現,考慮到審覈人員的安全意識良莠不齊,因此爲防止不安全的事情發生,圖片增長水印的工做是必需要作的。javascript
首先,考慮到業務場景,現階段的問題只是在審覈過程當中擔憂數據的泄露,咱們暫時只考慮顯式水印,既在圖片上增長一些能夠區別你我的身份的文字或者其餘數據。這樣就能夠作到根據泄露的數據能夠追查到我的,固然,未雨綢繆,防患於未然的警示功能纔是它最主要。css
水印的實現方式有不少,根據實現功能的人員分工能夠分爲前端水印和後端水印,前端水印的優勢能夠總結爲三點,第一,能夠不佔用服務器資源,徹底依賴客戶端的計算能力,減小服務端壓力。第二,速度快,不管哪一種前端的實現方式,性能都是優於後端的。第三,實現方式簡單。後端實現水印的最大優點也能夠總結爲三點,就是安全,安全,安全。知乎,微博都是採用後端實現的水印方案。可是綜合考慮,咱們仍是採用前端實現水印的方案。下面也會簡單介紹下 nodejs 怎麼實現後端圖片水印。前端
提供三個 npm 包,本部分不是咱們文章的重點,只提供簡單的 demo。java
1,gm github.com/aheckmann/g… 6.4k starnode
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;react
2,node-images:github.com/zhangyuanwe…git
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 //保存圖片到文件,圖片質量爲50
});
複製代碼
不須要安裝其餘工具,輕量級,zhangyuanwei 國人開發,中文文檔;github
3,jimp:github.com/oliver-mora… 可搭配 gifwrap 實現 gif 水印;npm
1,背景圖實現全屏水印canvas
能夠到阿里內外我的信息頁面查看效果,原理:
優勢:圖片是後端生成,安全;
缺點:須要發起 http 請求,獲取圖片信息;
效果展現:因爲是內部系統,不方便展現效果。
2,dom 實現全圖水印和圖片水印
在圖片的 onload 事件裏獲取圖片寬高,根據圖片大小生成水印區域,遮擋在圖片上層,dom 內容爲水印的文案或者其餘信息,實現方式比較簡單。
const wrap = document.querySelector('#ReactApp');
const { clientWidth, clientHeight } = wrap;
const waterHeight = 120;
const waterWidth = 180;
// 計算個數
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');
// 動態設置偏移值
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 = '測試水印';
wrap.appendChild(waterDom);
}
}
複製代碼
優勢:簡單易實現;
缺點:圖片過大或者過多會有性能影響;
效果展現:
3,canvas 實現方式(初版實現方案)
方法一:直接在圖片上操做
廢話很少說,直接上代碼
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;
// 設置水印
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);
// 設置水印浮層
const pattern = context.createPattern(innerCanvas, 'repeat');
context.fillStyle = pattern;
context.fill();
} catch (err) {
console.info(err);
setShowImg(true);
}
};
image.onerror = function () {
setShowImg(true);
};
}, [src]);
複製代碼
優勢:純前端實現方式,右鍵複製的圖片也是有水印的;
缺點:不支持 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({})})` }} />
複製代碼
優勢:純前端實現方式,支持跨域,支持 git 圖水印;
缺點:生成的 base64 url 比較大;
效果展現:下文給出。
其實根據這兩種 canvas 的實現方式能夠輕鬆的想出第三種方式,就是在圖片的上層遮一層 第一方法中的非圖片的 canvas,這樣就能完美的避免兩種方案的缺點。可是停留片刻想一下,兩種方案的結合,仍是使用 canvas 去繪製,是否是有更簡單易懂的方式呢。對,用 svg 替代。
4,SVG 方式(正在使用的方案)
給出一個 react 版的水印組件。
export const WaterMark = (props) => {
// 獲取水印數據
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;
// 設置背景圖和背景圖樣式
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="圖片加載錯誤" helpText="點擊複製圖片連接" /> : ( <> <img onLoad={onLoad} referrerPolicy="no-referrer" onError={onError} src={src} alt="圖片顯示錯誤" /> <Icon className={styles.img_loading} type="loading" /> </>
)
}
</div>
);
};
複製代碼
優勢:支持 gif 圖水印,不存在跨域問題,使用 repeat 屬性,無插入 dom 過程,無性能問題;
缺點:。。。
dom 結構展現:
5,效果圖展現
canvas 和 svg 實現的效果在展現上沒有很大的區別,因此效果圖就一張圖所有展現了。
問題一:若是把 watermark 的 dom 刪除了,圖片不就是無水印了嗎?
答案:能夠利用 MutationObserver 監聽 water 的節點,若是節點被修改,圖片也隨之隱藏;
問題二:鼠標右鍵複製圖片?
答案:所有的圖片都禁用了右鍵功能
問題三:若是從控制檯的network獲取圖片信息呢?
答案:此操做暫時沒有想到好的解決辦法,建議採用後端實現方案
前端實現的水印方案始終只是一種臨時方案,業務後端實現又耗費服務器資源,其實最理想的解決方式就是提供一個獨立的水印服務,雖然加載過程當中會略有延遲,可是相對與數據安全來講,毫秒級的延遲仍是能夠接受的,這樣又能保證不影響業務的服務穩定性。
在天天的答疑過程當中,也會有不少業務方來找我溝通水印遮擋風險點的問題,每次只能用數據安全的重要性來回復他們,固然,水印的大小,透明度,密集程度也都在不斷的調優中,相信會有一個版本,既能起到水印的做用,也能更好的解決遮擋問題。
做者:ES2049 / 卜露
文章可隨意轉載,但請保留此原文連接。
很是歡迎有激情的你加入 ES2049 Studio,簡歷請發送至 caijun.hcj@alibaba-inc.com 。