图片加水印

297 阅读1分钟

前言

在实际场景给图片加水印,在网上搜索很多工具需要进行上传图片,关键是图片涉及个人信息,并且很多站点都是广告。在这样的情况下,决定使用前端技术来自己实现图片加水印功能。

核心原理

1、canvas 的 drawImage 可以实现绘制图片;

2、canvas 的 fillText 可以实现新增文字。

图片上传到浏览器并实现 canvas 绘制

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="file" name="image" id="image" accept="image/">
  <canvas id="canvas"></canvas>
  <script>
    const canvas = document.getElementById('canvas')
    const context = canvas.getContext('2d')
    document.getElementById('image').addEventListener('change', function(e){
      const file = e.target.files[0]
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onloadend = () => {
        const image = new Image()
        image.src = reader.result
        image.onload = function(){
          canvas.width = image.width
          canvas.height = image.height
          context.drawImage(image, 0, 0, image.width, image.height) 
        }
      }
    })
  </script>
</body>
</html>

新增水印及属性控制

常见的水印是倾斜的,类似于在 canvas 上加蒙版然后进行旋转。fillStyle 用于控制样式。

context.fillStyle = 'rgba(255, 255, 255, 0.2)'
context.fillRect(0, 0, image.width, image.height)
context.rotate(-15 * Math.PI / 180)
context.fillStyle = 'rgba(0, 0, 0, 0.2)'
context.fillText("Hello World!", 10, 50)

在这里就成功加上了一个水印,将其中一些参数化即可实现水印的属性控制,比如:颜色,透明度,水印数量等,详情请看[代码仓](Efrice/watermark: Add watermark to image (github.com))。