canvas水印图片

该代码段展示了如何将Blob对象转换为dataURL,然后将dataURL转回Blob,进一步转化为File。此外,它提供了一个功能,用于在图片上添加水印,包括设置旋转角度、最大宽度、间隔和时间戳,最终返回带有水印的新dataURL。
摘要由CSDN通过智能技术生成
import { dateFormat } from "@/utils/LJTUtils/common/utils.js";
// 将File(Blob)对象转变为一个dataURL字符串, 即base64格式
export const fileToDataURL = file =>
  new Promise(resolve => {
    const reader = new FileReader();
    reader.onloadend = e => resolve(e.target.result);
    reader.readAsDataURL(file);
  });

//1,先将base64转换为blob
export function dataURLtoBlob(dataurl) {
  var arr = dataurl.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 });
}

//2,再将blob转换为file
export function blobToFile(theBlob, fileName) {
  theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
  theBlob.name = fileName; // 文件名
  return new File([theBlob], fileName, { type: theBlob.type, lastModified: Date.now() });
}

/*
 获取页面上需要合成水印的 img 元素,或者根据一个 File 或 Blob 对象,创建一个空的 img 元素,将其 src 设为 File 或 Blob 对象的 URL。

设置 canvas 元素的宽高为 img 元素的宽高,清除画布,绘制图像。
*/

export function draw(text, _base64) {
  const rotate = -20;
  const MAX_WIDTH = 350;
  const offsetY = 90;
  const gap = 50;
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = _base64;

    img.onload = function () {
      try {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        let { width: originWidth, height: originHeight } = img;

        // console.log("orgin", originWidth, originHeight);

        originHeight = ((MAX_WIDTH * originHeight) / originWidth).toFixed(2);
        originWidth = MAX_WIDTH;
        // console.log("target", originWidth, originHeight);
        canvas.width = originWidth;
        canvas.height = originHeight;

        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        // console.log(ctx);
        // console.log(ctx.font);
        // 设置笔触样式,font的样式一定要在measureText方法调用前
        ctx.font = "12px sans-serif";
        ctx.fillStyle = "#C5C5C5";
        // ctx.fillStyle = "rgba(0, 0, 0, .4)";
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";
        const txt = text + "  " + dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss");

        // 计算字符串的横向与纵向间距,设置了font的大小与字体
        const offsetX = Math.ceil(ctx.measureText(txt).width) + gap;

        // 列/行数
        const rowCount = Math.ceil(originHeight / offsetY);
        const colCount = Math.ceil((MAX_WIDTH * 2) / offsetX);

        // 旋转
        ctx.translate(-MAX_WIDTH / 2, offsetY);
        ctx.rotate((rotate * Math.PI) / 180);

        // 行
        for (let i = 0; i < rowCount; i++) {
          // 列
          for (let j = 0; j < colCount; j++) {
            const flag = i % 2 === 0;
            ctx.fillText(txt, flag ? offsetX * j : offsetX * j - gap, offsetY * i);
          }
        }

        resolve(canvas.toDataURL("image/jpeg", 0.4));
      } catch (e) {
        console.log("e", e);
        reject(e);
      }
    };
  });
}



export async function addWater(file, umNo) {
  const base64 = await fileToDataURL(file);
  return draw(umNo, base64);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值