天天看点

ionic给图片加水印

测试

【html】

<input type="file" accept="image/*" multiple (change)="selectPicture($event)" />
           

【ts】

selectPicture(event: any) {
    let file = event.target.files[0];
    //获取日期与时间
    let myDate = new Date();
    this.utils.watermarking(file, 11.01312, 28.21249, "湖南省长沙市芙蓉区马王堆街道长沙晚报报业集团", myDate.toLocaleString('chinese', { hour12: false }), (base64) => {
      this.imgPath = base64;
    })
}
           

使用canvas给图片加水印

watermarking(file: string, lng: number, lat: number, location: string, date: string, callback) {
    //新建img对象 
    var img = new Image();
    img.src = file;
    // img加载完成
    img.onload = function () {
      //准备canvas
      var canvas = document.createElement("canvas");
      canvas.setAttribute("width", img.width + "");
      canvas.setAttribute("height", img.height + "");
      var context = canvas.getContext("2d");
      // 绘制图片
      context.drawImage(img, 0, 0);
      // 绘制水印
      context.font = "italic normal lighter 10px arial";
      context.fillStyle = "rgba(255,255,255,1)";
      //经度
      context.fillText("经度:" + lng, 5, img.height - 70);
      //纬度
      context.fillText("纬度:" + lat, 5, img.height - 50);
      //位置
      context.fillText("位置:" + location, 5, img.height - 30);
      //时间
      context.fillText("时间:" + date, 5, img.height - 10);
      var newBase64 = canvas.toDataURL("image/jpeg"); //压缩语句
      callback(newBase64);//必须通过回调函数返回,否则无法及时拿到该值
    }
}
           

js获取系统时间并转化为24小时模式

let myDate = new Date();
let currentDate = myDate.toLocaleString('chinese', { hour12: false });