wx uni canvas 压缩图片,加水印,离线存储图片

507 阅读1分钟

压缩图片

      	cosnt ctx = wx.createCanvasContext( "firstCanvas",this); 
          /** 创建画布 */
          //将图片src放到cancas内,宽高为图片大小
          
          ctx.drawImage(tempFilePath, 0, 0, width, height);
          ctx.setFontSize(12);
          ctx.setFillStyle("#fff");
          let textToWidth = width * 0.3; /*  (ress.width / 3) * 0.5 */
          let textToHeight = height * 0.5; /*  (ress.height / 3) * 0.3 */
          
          ctx.fillText(
            formatDate(Date.parse(new Date())),
            textToWidth,
            textToHeight
          );
          
          ctx.draw(false, () => {
            setTimeout(() => {
            //处理图片寸尺
              uni.canvasToTempFilePath(
                {
                  x: 0,
                  y: 0,
                  canvasId: "firstCanvas",
                  success: (res1) => {
                  //这里存储是需要注意,会出现
                    that.storageImage            
                    uni.hideLoading();
                  },
                  fail(err) {
                    uni.hideLoading();
                  },
                },
                that
              );
            }, 500);
          });

存储时再图片预览时,安卓和ios再 企业微信中的(previewImage)会出现黑屏,找不到图片路径

再企业微信中会出现很多问题 我们需要判断机型去如何存储图片

storageImage(res, type){
	const tempFilePath = res.tempFilePath;
    const res = wx.getSystemInfoSync();
    this.platform = res.platform === "android" ? "android" : "";
   //ios 需要用 wx.getFileSystemManager()
   // 安卓可以直接用saveFile() 存储  ios会出现 getSavedFileList 找不到情况
   const path = `${wx.env.USER_DATA_PATH}`,
   const xx2 =  wx.getFileSystemManager()
   // 存储 filePath ,安卓/和ios需要注意路径问题 引用这个需要注意  path后需不要叫加/ 因为再ios需要添加一个/ 而安卓不能添加/开发是一定注意,因为图片预览的时候会出现黑屏wx.previewImage
   //`${path}/${Date.now()}_${type}.jpg`;
   const filePath
   xx2.saveFile({
    filePath,
    tempFilePath, 
   })
}

次程序只能再微信中调用,所以直接用的wx没有用uni