天天看點

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 });