遇到问题

日常工作中,常常会遇到很多敏感的数据,为避免数据的泄露,咱们要在数据上做一些”包装“。目标就是让那些有心泄露数据的”不法分子“迫于重大的”舆论压力“而放弃不法行为,使之”立功得逞“,达到不战而屈人之兵的成果。而在安全部门工作的咱们,数据安全的观点早已深入骨髓,每个文字,每张图片,都要留心是否有泄露的危险,怎么避免数据泄露,是咱们始终思考的问题。比方图片的水印,就是咱们工作过程中常常波及到的问题。因为自身工作内容就是审核平台的开发,常常有一些危险图片会在审核平台呈现,思考到审核人员的安全意识参差不齐,所以为避免不平安的事件产生,图片减少水印的工作是必须要做的。

剖析问题

首先,思考到业务场景,现阶段的问题只是在审核过程中放心数据的泄露,咱们临时只思考显式水印,既在图片上减少一些能够区别你个人身份的文字或者其余数据。这样就能够做到依据泄露的数据能够追究到集体,当然,防患未然,防患于未然的警示性能才是它最次要。

解决问题

实现形式

水印的实现形式有很多,依据实现性能的人员分工能够分为前端水印和后端水印,前端水印的长处能够总结为三点,第一,能够不占用服务器资源,齐全依赖客户端的计算能力,缩小服务端压力。第二,速度快,无论哪种前端的实现形式,性能都是优于后端的。第三,实现形式简略。后端实现水印的最大劣势也能够总结为三点,就是平安,平安,平安。知乎,微博都是采纳后端实现的水印计划。然而综合思考,咱们还是采纳前端实现水印的计划。上面也会简略介绍下 nodejs 怎么实现后端图片水印。

node实现

提供三个 npm 包,本局部不是咱们文章的重点,只提供简略的 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                    //保留图片到文件,图片品质为50    });

不须要装置其余工具,轻量级,zhangyuanwei 国人开发,中文文档;
3,jimp:https://github.com/oliver-moran/jimp
可搭配 gifwrap 实现 gif 水印;

前端实现

1,背景图实现全屏水印
能够到阿里内外个人信息页面查看成果,原理:

长处:图片是后端生成,平安;
毛病:须要发动 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 实现的成果在展现上没有很大的区别,所以效果图就一张图全副展现了。

QA

问题一:
如果把 watermark 的 dom 删除了,图片不就是无水印了吗?
答案:
能够利用 MutationObserver 监听 water 的节点,如果节点被批改,图片也随之暗藏;
问题二:
鼠标右键复制图片?
答案:
全副的图片都禁用了右键性能
问题三:
如果从控制台的network获取图片信息呢?
答案:
此操作临时没有想到好的解决办法,倡议采纳后端实现计划

总结

前端实现的水印计划始终只是一种长期计划,业务后端实现又消耗服务器资源,其实最现实的解决形式就是提供一个独立的水印服务,尽管加载过程中会略有提早,然而绝对与数据安全来说,毫秒级的提早还是能够承受的,这样又能保障不影响业务的服务稳定性。
在每天的答疑过程中,也会有很多业务方来找我沟通水印遮挡危险点的问题,每次只能用数据安全的重要性来回复他们,当然,水印的大小,透明度,密集水平也都在一直的调优中,置信会有一个版本,既能起到水印的作用,也能更好的解决遮挡问题。

作者:ES2049 /卜露
文章可随便转载,但请保留此原文链接。
十分欢送有激情的你退出 ES2049 Studio,简历请发送至 caijun.hcj@alibaba-inc.com 。