搜尋
首頁web前端前端問答怎麼實現浮水印?淺析水印實現的幾種方式

怎麼實現浮水印?這篇文章給大家分享幾種浮水印實現的方式,有需要的朋友可以學習了解一下~

怎麼實現浮水印?淺析水印實現的幾種方式

遇到問題

#在日常工作中,經常會遇到很多敏感的數據,為防止數據的洩露,我們要在數據上做一些」包裝「。目的就是讓那些有心洩露資料的」不法分子「迫於嚴重的」輿論壓力「而放棄不法行為,使之」犯罪未遂“,達到不戰而屈人之兵的效果。而在安全部門工作的我們,資料安全的觀念早已深入骨髓,每個文字,每張圖片,都要留心是否有洩露的風險,怎麼防止資料洩露,是我們一直在思考的問題。例如圖片的浮水印,就是我們工作過程中常涉及的問題。因為本身工作內容就是審核平台的開發,經常有一些風險圖片會在審核平台出現,考慮到審核人員的安全意識參差不齊,所以為防止不安全的事情發生,圖片增加水印的工作是必須要做的。

分析問題

首先,考慮到業務場景,現階段的問題只是在審核過程中擔心資料的洩露,我們暫時只考慮顯式水印,既在圖片上增加一些可以區別你個人身份的文字或其他資料。這樣就可以做到根據洩漏的資料可以追蹤到個人,當然,未雨綢繆,防患於未然的警示功能才是它最主要。

解決問題

實現方式

#水印的實作方式有很多,根據實作功能的人員分工可以分為前端浮水印和後端浮水印,前端浮水印的優點可以總結為三點,第一,可以不佔用伺服器資源,完全依賴客戶端的運算能力,減少服務端壓力。第二,速度快,無論哪一種前端的實作方式,效能都是優於後端的。第三,實作方式簡單。後端實現水印的最大優勢也可以總結為三點,就是安全,安全,安全。知乎,微博都是採用後端實現的水印方案。但綜合考慮,我們還是採用前端實現浮水印的方案。下面也會簡單介紹下 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(&#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);
    }
}

優點:簡單易實作;

缺點:圖片過大或過多會有效能影響;

效果顯示:

3,canvas 實作方式(第一版實作方案)

方法一:直接在圖片上操作

廢話不多說,直接上程式碼

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]);
優點:純前端實作方式,右鍵複製的圖片也是有浮水印的;

缺點:不支援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 = &#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="/static/imghwm/default1.png"  data-src="https://xxx.xxx.jpg"  class="lazy"   / alt="怎麼實現浮水印?淺析水印實現的幾種方式" >
<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(&#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 src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/image/323/319/107/1629255185289626.png?x-oss-process=image/resize,p_40"  class="lazy"  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获取图片信息呢?

答案:

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

总结

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

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

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

作者:ES2049 /卜露

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

以上是怎麼實現浮水印?淺析水印實現的幾種方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:知乎。如有侵權,請聯絡admin@php.cn刪除
反應的局限性是什麼?反應的局限性是什麼?May 02, 2025 am 12:26 AM

Include:1)AsteeplearningCurvedUetoItsVasteCosystem,2)SeochallengesWithClient-SiderEndering,3)潛在的PersperformanceissuesInsuesInlArgeApplications,4)ComplexStateStateManagementAsappsgrow和5)TheneedtokeEedtokeEedtokeEppwithitsrapideDrapidevoltolution.thereedtokeEppectortorservolution.thereedthersrapidevolution.ththesefactorsshesssheou

React的學習曲線:新開發人員的挑戰React的學習曲線:新開發人員的挑戰May 02, 2025 am 12:24 AM

reactischallengingforbeginnersduetoitssteplearningcurveandparadigmshifttocoment oparchitecent.1)startwithofficialdocumentationforasolidFoundation.2)了解jsxandhowtoembedjavascriptwithinit.3)

為React中的動態列表生成穩定且獨特的鍵為React中的動態列表生成穩定且獨特的鍵May 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript疲勞:與React及其工具保持最新JavaScript疲勞:與React及其工具保持最新May 02, 2025 am 12:19 AM

javascriptfatigueinrectismanagbaiblewithstrategiesLike just just in-timelearninganning and CuratedInformationsources.1)學習whatyouneedwhenyouneedit

使用USESTATE()掛鉤的測試組件使用USESTATE()掛鉤的測試組件May 02, 2025 am 12:13 AM

tateractComponents通過theusestatehook,使用jestandReaCtTestingLibraryToSigulationsimintionsandIntractions and verifyStateChangesInTheUI.1)underthecomponentAndComponentAndComponentAndConconentAndCheckInitialState.2)模擬useruseruserusertactionslikeclicksorformsorformsormissions.3)

React中的鑰匙:深入研究性能優化技術React中的鑰匙:深入研究性能優化技術May 01, 2025 am 12:25 AM

KeysinreactarecrucialforopTimizingPerformanceByingIneFefitedListupDates.1)useKeyStoIndentifyAndTrackListelements.2)避免使用ArrayIndi​​cesasKeystopreventperformansissues.3)ChooSestableIdentifierslikeIdentifierSlikeItem.idtomaintainAinainCommaintOnconMaintOmentStateAteanDimpperperFermerfermperfermerformperfermerformfermerformfermerformfermerment.ChosestopReventPerformissues.3)

反應中的鍵是什麼?反應中的鍵是什麼?May 01, 2025 am 12:25 AM

ReactKeySareUniqueIdentifiers usedwhenrenderingListstoimprovereConciliation效率。 1)heelPreactrackChangesInListItems,2)使用StableanDuniqueIdentifiersLikeItifiersLikeItemidSisRecumended,3)避免使用ArrayIndi​​cesaskeyindicesaskeystopreventopReventOpReventSissUseSuseSuseWithReRefers和4)

反應中獨特鍵的重要性:避免常見的陷阱反應中獨特鍵的重要性:避免常見的陷阱May 01, 2025 am 12:19 AM

獨特的keysarecrucialinreactforoptimizingRendering和MaintainingComponentStateTegrity.1)useanaturalAlaluniqueIdentifierFromyourDataiFabable.2)ifnonaturalalientedifierexistsistsists,generateauniqueKeyniqueKeyKeyLiquekeyperaliqeyAliqueLiqueAlighatiSaliqueLiberaryLlikikeuuId.3)deversearrayIndi​​ceSaskeyseSecialIndiceSeasseAsialIndiceAseAsialIndiceAsiall

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境