How to implement watermark? A brief analysis of several ways to achieve watermarking

青灯夜游
Release: 2021-08-18 10:57:55
forward
1947 people have browsed it

How to implement watermark? This article will share with you several ways to implement watermarks. Friends in need can learn about it~

How to implement watermark? A brief analysis of several ways to achieve watermarking

Encountered problems

In daily work, we often encounter a lot of sensitive data. In order to prevent data leakage, we need to do some "packaging" on the data. The purpose is to make those "criminal elements" who are interested in leaking data give up their illegal behavior under severe "pressure of public opinion" and make them "criminal attempts" to achieve the effect of defeating others without fighting. As for those of us who work in the security department, the concept of data security has long been ingrained in our bones. Every word and every picture must be mindful of whether there is a risk of leakage. How to prevent data leakage is a question we have been thinking about. For example, the watermark of pictures is an issue we often encounter in our work process. Because my job content is the development of the review platform, some risky pictures often appear on the review platform. Considering that the security awareness of reviewers is uneven, in order to prevent unsafe things from happening, it is necessary to add watermarks to the pictures. of.

Analysis of Problems

First of all, considering the business scenario, the problem at this stage is just worrying about data leakage during the audit process. We only consider explicit watermarks for the time being. Add some text or other data to the picture that can identify you personally. In this way, individuals can be traced based on the leaked data. Of course, its most important function is to take precautions and prevent problems before they occur.

Solution to the problem

Implementation methods

There are many ways to implement watermarks, which can be divided into Front-end watermarking and back-end watermarking. The advantages of front-end watermarking can be summarized in three points. First, it does not occupy server resources and relies entirely on the computing power of the client, reducing pressure on the server. Second, it is fast. No matter which front-end implementation is implemented, the performance is better than the back-end. Third, the implementation is simple. The biggest advantage of implementing watermarking on the backend can also be summarized in three points, namely safety, safety, and safety. Zhihu and Weibo both use back-end watermark solutions. However, after comprehensive consideration, we still adopt the front-end solution to implement watermarking. The following will also briefly introduce how nodejs implements back-end image watermarking.

node implementation

Provides three npm packages. This part is not the focus of our article, only a simple demo is provided.

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');
});
Copy after login

Requires GraphicsMagick or ImageMagick to be installed;

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
    });
Copy after login

No need to install other tools, lightweight, developed by zhangyuanwei Chinese, Chinese documentation;

3, jimp: https://github.com/oliver-moran/jimp

can be used with gifwrap to implement gif watermark;

Front-end implementation

1, the background image implements full-screen watermark

You can check the effect on the personal information page inside and outside Alibaba. Principle:

How to implement watermark? A brief analysis of several ways to achieve watermarking

Advantages: The picture is generated by the back end and is safe;

Disadvantage: Need to initiate an http request to obtain the picture information;

Effect display: Because it is internal system, it is inconvenient to display the effect.

2, dom implements full image watermark and image watermark

Get the image width and height in the onload event of the image, generate the watermark area according to the image size, and block it on the upper layer of the image , the DOM content is watermark copywriting or other information, and the implementation method is relatively simple.

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(&#39;div&#39;);
        // 动态设置偏移值
        waterDom.setAttribute(&#39;style&#39;, `
            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 = &#39;测试水印&#39;;
        wrap.appendChild(waterDom);
    }
}
Copy after login

Advantages: simple and easy to implement;

Disadvantages: too large or too many pictures will affect performance;

Effect display:

How to implement watermark? A brief analysis of several ways to achieve watermarking

3, canvas implementation method (first version implementation plan)

Method 1: Operate directly on the picture

Without further ado, let’s go directly to the code

useEffect(() => {
      // gif 图不支持
    if (src && src.includes(&#39;.gif&#39;)) {
      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 = &#39;hanging&#39;;
        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(&#39;2d&#39;);
        context.drawImage(this, 0, 0);
        context.rect(0, 0, image.width || 200, image.height || 200);
           // 设置水印浮层
        const pattern = context.createPattern(innerCanvas, &#39;repeat&#39;);
        context.fillStyle = pattern;
        context.fill();
      } catch (err) {
        console.info(err);
        setShowImg(true);
      }
    };
    image.onerror = function () {
      setShowImg(true);
    };
  }, [src]);
Copy after login

Advantages: Pure front-end implementation, the pictures copied by right-clicking are also watermarked;

Disadvantages: GIF is not supported, and the picture must support cross-domain;

Effect display: given below.

Method 2: canvas generates watermark url and assigns it to css background attribute

export const getBase64Background = (props) => {
  const { nick, empId } = GlobalConfig.userInfo;
  const {
    rotate = -20,
    height = 75,
    width = 85,
    text = `${nick}-${empId}`,
    fontSize = &#39;14px&#39;,
    lineWidth = 2,
    fontFamily = &#39;microsoft yahei&#39;,
    strokeStyle = &#39;rgba(255, 255, 255, .15)&#39;,
    fillStyle = &#39;rgba(0, 0, 0, 0.15)&#39;,
    position = { x: 30, y: 30 },
  } = props;
  const image = new Image();
  image.crossOrigin = &#39;Anonymous&#39;;
  const canvas = document.createElement(&#39;canvas&#39;);
  const context = canvas.getContext(&#39;2d&#39;);
  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 = &#39;center&#39;;
  context.textBaseline = &#39;hanging&#39;;
  context.strokeText(text, position.x, position.y);
  context.fillText(text, position.x, position.y);
  return canvas.toDataURL(&#39;image/png&#39;);
};

// 使用方式 
<img  src="https://xxx.xxx.jpg" / alt="How to implement watermark? A brief analysis of several ways to achieve watermarking" >
<div className="warter-mark-area" style={{ backgroundImage: `url(${getBase64Background({})})` }} />
Copy after login

Advantages: pure front-end implementation, supports cross-domain, and supports git image watermark;

Disadvantages: The generated base64 url ​​is relatively large;

Effect display: given below.

In fact, based on the implementation of these two canvases, you can easily come up with the third way, which is to cover the upper layer of the picture with a non-picture canvas in the first method, so that you can perfectly avoid the two problems. Disadvantages of this plan. But stop for a moment and think about it. Is there a simpler and easier way to combine the two solutions and use canvas to draw? Yes, use svg instead.

4, SVG method (the solution being used)

Gives a react version of the watermark component.

export const WaterMark = (props) => {
  // 获取水印数据
  const { nick, empId } = GlobalConfig.userInfo;
  const boxRef = React.createRef();
  const [waterMarkStyle, setWaterMarkStyle] = useState(&#39;180px 120px&#39;);
  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=\&#39;100%\&#39; height=\&#39;100%\&#39; xmlns=\&#39;http://www.w3.org/2000/svg\&#39; version=\&#39;1.1\&#39;><text width=\&#39;100%\&#39; height=\&#39;100%\&#39; x=\&#39;20\&#39; y=\&#39;68\&#39;  transform=\&#39;rotate(-20)\&#39; fill=\&#39;rgba(0, 0, 0, 0.2)\&#39; font-size=\&#39;14\&#39; stroke=\&#39;rgba(255, 255, 255, .2)\&#39; stroke-width=\&#39;1\&#39;>${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(&#39;px&#39;, &#39;&#39;)) < 180) {
      setWaterMarkStyle(`${width} ${height.replace(&#39;px&#39;, &#39;&#39;) / 2}px`);
    };
    previousSibling.style.height = height;
    previousSibling.style.width = width;
    previousSibling.style.top = `${offsetTop}px`;
    previousSibling.style.left = `${offsetLeft}px`;
    // 加载 loading 隐藏
    nextSibling.style.display = &#39;none&#39;;
  };
  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>
  );
};
Copy after login

优点:支持 gif 图水印,不存在跨域问题,使用 repeat 属性,无插入 dom 过程,无性能问题;
缺点:。。。

dom 结构展示:

How to implement watermark? A brief analysis of several ways to achieve watermarking

5,效果图展示

canvas 和 svg 实现的效果在展示上没有很大的区别,所以效果图就一张图全部展示了。

How to implement watermark? A brief analysis of several ways to achieve watermarking

QA

问题一:

如果把 watermark 的 dom 删除了,图片不就是无水印了吗?

答案:

可以利用 MutationObserver 监听 water 的节点,如果节点被修改,图片也随之隐藏;

问题二:

鼠标右键复制图片?

答案:

全部的图片都禁用了右键功能

问题三:

如果从控制台的network获取图片信息呢?

答案:

此操作暂时没有想到好的解决办法,建议采用后端实现方案

总结

前端实现的水印方案始终只是一种临时方案,业务后端实现又耗费服务器资源,其实最理想的解决方式就是提供一个独立的水印服务,虽然加载过程中会略有延迟,但是相对与数据安全来说,毫秒级的延迟还是可以接受的,这样又能保证不影响业务的服务稳定性。

在每天的答疑过程中,也会有很多业务方来找我沟通水印遮挡风险点的问题,每次只能用数据安全的重要性来回复他们,当然,水印的大小,透明度,密集程度也都在不断的调优中,相信会有一个版本,既能起到水印的作用,也能更好的解决遮挡问题。

原文地址:https://segmentfault.com/a/1190000040425430

作者:ES2049 /卜露

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of How to implement watermark? A brief analysis of several ways to achieve watermarking. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:zhihu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!