首頁  >  文章  >  web前端  >  淺析利用nodejs怎麼為圖片加上半透明浮水印(方法詳解)

淺析利用nodejs怎麼為圖片加上半透明浮水印(方法詳解)

青灯夜游
青灯夜游轉載
2022-02-22 19:38:563383瀏覽

怎麼利用nodejs為圖片加浮水印?以下這篇文章透過範例來介紹一下使用node為圖片添加全頁半透明浮水印的方法,希望對大家有幫助!

淺析利用nodejs怎麼為圖片加上半透明浮水印(方法詳解)

作為中後台專案的匯出功能,通常會被要求具備導出的追溯能力。

當匯出的資料形態為圖片時,一般會為圖片添加浮水印以達到此目的。

DEMO

那麼在匯出圖片前如何為其添加上可以作為匯出者識別的水印呢?先看成品:

淺析利用nodejs怎麼為圖片加上半透明浮水印(方法詳解)

上圖原圖為我隨便在網路上找的一張圖片,加入浮水印之後的效果如圖所示。

業務需求分解

這裡我們需要考慮在這個業務場景之下,這個需求的三個要點:

  • #水印需要鋪滿整個圖片
  • 水印文字成半透明狀,確保原圖的可讀性
  • 水印文字應清晰可讀

選型

如我一樣負責在一個node.js server上實現以上需求,可選項相當多,例如直接使用c lib imagemagick或已有人封裝的各種node watermarking函式庫。在本文中,我們將選擇使用對Jimp庫的封裝。

Jimp 函式庫的官方github頁面上這樣描述它自己:

An image processing library for Node written entirely in JavaScript, with zero native dependencies.

並且提供為數眾多的操作圖片的API

  • blit - Blit an image onto another.
  • blur - Quickly blur an image.
  • #color - Various color manipulation methods.
  • contain - Contain an image within a height and width.
  • #cover - Scale the image so the given width and height keeping the aspect ratio.
  • displace - Displaces the image based on a displacement map
  • dither - Apply a dither effect to an image.
  • flip - Flip an image along it's x or y axis.
  • #gaussian - Hardcore blur.
  • invert - Invert an images colors
  • mask - Mask one image with another.
  • #normalize - Normalize the colors in an image
  • print - Print text onto an image
  • resize - Resize an image.
  • #rotate - Rotate an image.
  • scale - Uniformly scales the image by a factor.

在本文所述的業務場景中,我們只需使用其中部分API即可。

設計與實作

input 參數設計:

  • url: 原始圖片的儲存位址(對於Jimp來說,可以是遠端位址,也可以是本機位址)
  • textSize: 需新增的浮水印文字大小
  • opacity:透明度
  • text:需要新增的浮水印文字
  • dstPath:新增浮水印之後的輸出圖片位址,位址為腳本執行目錄的相對路徑
  • rotate:水印文字的旋轉角度
  • colWidth:因為可旋轉的浮水印文字是作為一張圖片覆蓋到原圖上的,因此這裡定義一下水印圖片的寬度,預設為300像素
  • rowHeight:理由同上,水印圖片的高度,預設為50像素。 (PS:這裡的水印圖片尺寸可以大致理解為水印文字的間隔)

因此在該模組的coverTextWatermark函數中對外暴露以上參數即可

coverTextWatermark

/**
 * @param {String} mainImage - Path of the image to be watermarked
 * @param {Object} options
 * @param {String} options.text     - String to be watermarked
 * @param {Number} options.textSize - Text size ranging from 1 to 8
 * @param {String} options.dstPath  - Destination path where image is to be exported
 * @param {Number} options.rotate   - Text rotate ranging from 1 to 360
 * @param {Number} options.colWidth - Text watermark column width
 * @param {Number} options.rowHeight- Text watermark row height
 */

module.exports.coverTextWatermark = async (mainImage, options) => {
  try {
    options = checkOptions(options);
    const main = await Jimp.read(mainImage);
    const watermark = await textWatermark(options.text, options);
    const positionList = calculatePositionList(main, watermark)
    for (let i =0; i < positionList.length; i++) {
      const coords = positionList[i]
      main.composite(watermark,
        coords[0], coords[1] );
    }
    main.quality(100).write(options.dstPath);
    return {
      destinationPath: options.dstPath,
      imageHeight: main.getHeight(),
      imageWidth: main.getWidth(),
    };
  } catch (err) {
    throw err;
  }
}

textWatermark

Jimp不能直接將文字旋轉一定角度,並寫到原始圖片上,因此我們需要根據水印文字產生新的圖片二進制流,並將其旋轉。最終以這個新生成的圖片作為真正的水印添加到原始圖片上。以下是產生浮水印圖片的函數定義:

const textWatermark = async (text, options) => {
  const image = await new Jimp(options.colWidth, options.rowHeight, &#39;#FFFFFF00&#39;);
  const font = await Jimp.loadFont(SizeEnum[options.textSize])
  image.print(font, 10, 0, {
    text,
    alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
    alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE
  },
  400,
  50)
  image.opacity(options.opacity);
  image.scale(3)
  image.rotate( options.rotation )
  image.scale(0.3)
  return image
}

calculatePositionList

到目前为止原图有了,水印图片也有了,如果想达到铺满原图的水印效果,我们还需要计算出水印图片应该在哪些坐标上画在原图上,才能达成水印铺满原图的目的。

const calculatePositionList = (mainImage, watermarkImg) => {
  const width = mainImage.getWidth()
  const height = mainImage.getHeight()
  const stepWidth = watermarkImg.getWidth()
  const stepHeight = watermarkImg.getHeight()
  let ret = []
  for(let i=0; i < width; i=i+stepWidth) {
    for (let j = 0; j < height; j=j+stepHeight) {
      ret.push([i, j])
    }
  }
  return ret
}

如上代码所示,我们使用一个二维数组记录所有水印图片需出现在原图上的坐标列表。

总结

至此,关于使用Jimp为图片添加文字水印的所有主要功能就都讲解到了。

github地址:https://github.com/swearer23/jimp-fullpage-watermark

npm:npm i jimp-fullpage-watermark

Inspiration 致谢

https://github.com/sushantpaudel/jimp-watermark

https://github.com/luthraG/image-watermark

https://medium.com/@rossbulat/image-processing-in-nodejs-with-jimp-174f39336153

示例代码:

var watermark = require(&#39;jimp-fullpage-watermark&#39;);

watermark.coverTextWatermark(&#39;./img/main.jpg&#39;, {
  textSize: 5,
  opacity: 0.5,
  rotation: 45,
  text: &#39;watermark test&#39;,
  colWidth: 300,
  rowHeight: 50
}).then(data => {
    console.log(data);
}).catch(err => {
    console.log(err);
});

更多node相关知识,请访问:nodejs 教程

以上是淺析利用nodejs怎麼為圖片加上半透明浮水印(方法詳解)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.cn。如有侵權,請聯絡admin@php.cn刪除