使用图像作为 compressor.js 的水印

Use image as watermark with compressor.js

我正在使用 compressor.js 进行图像压缩和加水印。但是,我似乎只能使用基于文本的水印。我也想加图片(logo)到水印中。

知道如何将图像用作 compressor.js 的水印吗?

您可以使用 drew function 执行此操作,如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/compressorjs/1.0.7/compressor.min.js"></script>
</head>
<body>
  <img id="watermark" src="watermark.png" style="display: none" />
  <h3>Input</h3>
  <div id="input"><img id="image" src="picture.png" style="max-width:250px"></div>
  <h3>Output</h3>
  <div id="output"></div>
  <script>
    window.addEventListener('DOMContentLoaded', function () {
      var Compressor = window.Compressor;
      var URL = window.URL || window.webkitURL;
      var image = document.getElementById('image');   
      var output = document.getElementById('output');
      var watermark = document.getElementById('watermark');
      var xhr = new XMLHttpRequest();

      xhr.onload = function () {
        new Compressor(xhr.response, {
          strict: false,
          drew: function (context, canvas) {
            context.drawImage(
              watermark,
              0,
              0,
              watermark.width,
              watermark.height,
              canvas.width - ((watermark.width / 4) + 10),
              canvas.height - ((watermark.height / 4) + 10),
              (watermark.width / 4),
              (watermark.height / 4))
          },
          success: function (result) {
            var newImage = new Image();
            newImage.src = URL.createObjectURL(result);
            newImage.style = "max-width:250px";
            output.appendChild(newImage);
          },
          error: function (err) {
            window.alert(err.message);
          },
        });
      };

      xhr.open('GET', image.src);
      xhr.responseType = 'blob';
      xhr.send();
    });
  </script>
</body>
</html>

全部除以4是因为我的水印图片很大。这不是必需的。

这是 before/after 的屏幕截图: