用 JS 给图片加文字水印或图片水印

1.加文字水印

示例代码:

  function blobToImg(blob) {
    return new Promise((resolve, reject) => {
      let reader = new FileReader()
      reader.addEventListener('load', () => {
        let img = new Image()
        img.src = reader.result
        img.addEventListener('load', () => resolve(img))
      })
      reader.readAsDataURL(blob)
    })
  }

  function imgToCanvas(img) {
    let canvas = document.createElement('canvas')
    canvas.width = img.width
    canvas.height = img.height
    let ctx = canvas.getContext('2d')
    ctx.drawImage(img, 0, 0)
    return canvas
  }

  function watermark(canvas, text) {
    return new Promise((resolve, reject) => {
      let ctx = canvas.getContext('2d')
      // 设置填充字号和字体,样式
      ctx.font = "24px 宋体"
      ctx.fillStyle = "#FFC82C"
      // 设置右对齐
      ctx.textAlign = 'right'
      // 在指定位置绘制文字,这里指定距离右下角20坐标的地方
      ctx.fillText(text, canvas.width - 20, canvas.height - 20)
      canvas.toBlob(blob => resolve(blob))
    })
  }

  function imgWatermark(dom, text) {
    let input = document.createElement('input')
    input.setAttribute('type', 'file')
    input.setAttribute('accept', 'image/*')
    input.onchange = async () => {
      let img = await blobToImg(input.files[0])
      let canvas = imgToCanvas(img)
      let blob = await watermark(canvas, text)
      let newImage = await blobToImg(blob)
      dom.appendChild(newImage)
    }
    dom.appendChild(input)
  }

  let dom = document.querySelector('#container')
  imgWatermark(dom, '水印文字')

效果:

在这里插入图片描述

2.加图片水印

示例代码:

  drawAndShareImage();
  function drawAndShareImage() {
    let canvas = document.createElement("canvas");
    canvas.width = 500;
    canvas.height = 500;
    let context = canvas.getContext("2d");
    context.rect(0 , 0 , canvas.width , canvas.height);
    context.fillStyle = "#fff";
    context.fill();
    let myImage = new Image();
    myImage.src = "https://img1.baidu.com/it/u=4250523823,184246375&fm=26&fmt=auto&gp=0.jpg";  // 背景图片 你自己本地的图片或者在线图片
    myImage.crossOrigin = "Anonymous";
    myImage.onload = function() {
      context.drawImage(myImage, 0, 0, 500, 500);
  //     context.font = "60px Courier New";
  //     context.fillText("我是文字",350,450);
      let myImage2 = new Image();
      myImage2.src = "https://img-home.csdnimg.cn/images/20201124032511.png";  // 你自己本地的图片或者在线图片
      myImage2.crossOrigin = "Anonymous";
      myImage2.onload = function() {
        context.drawImage(myImage2 , 175 , 175 , 225 , 225);
        let base64 = canvas.toDataURL("image/png"); // "image/png" 这里注意一下
        let img = document.getElementById("avatar");
        // document.getElementById('avatar').src = base64;
        img.setAttribute("src", base64);
      }
    }
  }

效果:

在这里插入图片描述

实际业务中的代码:


	/**
	 * base64 类型转 Blob 类型
	 * @param {base64} base64
	 * @returns {Blob} blob
	 */
    base64ToBlob(base64) {
      let arr = base64.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    /**
     * 给图片增加图片水印
     * @param {File} file 图片
     * @returns {File} 增加水印后的图片
     */
    async addWatermark(file) {
      let blob = {};
      const _URL = window.URL || window.webkitURL;
      const img = new Image();
      img.src = _URL.createObjectURL(file);
      await new Promise(resolve => {
        img.onload = async () => {
          const canvas = document.createElement('canvas');
          canvas.width = img.width;
          canvas.height = img.height;
          const context = canvas.getContext('2d');
          context.drawImage(img, 0, 0);
          // 水印图片
          const watermarkImg = new Image();
          watermarkImg.src = require('@/assets/img/watermark.png'); // logo
          await new Promise(resolve => {
            watermarkImg.onload = () => {
              context.drawImage(watermarkImg, 0, 0);
              const base64 = canvas.toDataURL('image/png');
              blob = this.base64ToBlob(base64);
              resolve();
            }
          });
          resolve();
        };
      });
      return new File([blob], file.name, {
        type: file.type,
      });
    },
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值