图片相关的转换(image-conversion)

------------恢复内容开始------------

图片的base64转成文件流形式返回
 convertBase64ToBlob(dataURL) {
  var byteString = atob(dataURL.split(',')[1]);
  var mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
  }
  let blob = new Blob([ab], { type: mimeString });
  let file = new File([blob], Date.now() + '.png', { type: mimeString }) 
return file ;
 
 
file文件图片进行压缩转成base64
    compressPicture(file){
      //上传的图片进行压缩
      var reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        let data = e.target.result
        const img = new Image();
        img.src = data;
        img.onload = () => {
          // 使用 canvas 来缩放图片
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          const maxSize = 1024 * 1024; // 设置最大尺寸,例如1MB
          const width = img.width;
          const height = img.height;
          let ratio = 1; // 缩放比例
          if (width * height > maxSize) {
            ratio = Math.sqrt(maxSize / (width * height));
          }
          canvas.width = width * ratio;
          canvas.height = height * ratio;
            // 绘制并压缩图片
          ctx.drawImage(img, 0, 0, width, height, 0, 0, canvas.width, canvas.height);
          // 将Canvas转换回ImageData
        const base64 = canvas.toDataURL('image/jpeg', 1); // 0.7为压缩质量
     };
      }
    },

Vue中图片压缩的工具 image-conversion

  npm安装: npm install image-conversion --save

     调用 :import * as imageConversion from 'image-conversion';

//压缩质量
export function getCompressionQuality(isLtSize,imgType) {
if (isLtSize < 3) {
return 0.93;
} else if (isLtSize >= 3 && isLtSize < 5) {
return 0.90;
} else if (isLtSize >= 5 && isLtSize < 10) {
return 0.80;
} else if (isLtSize >= 10 && isLtSize < 20) {
return 0.70;
} else if (isLtSize >= 20 && isLtSize < 30) {
return 0.60;
}
return 0.90;
}

//压缩逻辑
export function compressImage(file, quality) {
return new Promise((resolve, reject) => {
imageConversion.compress(file, quality)
.then((res) => {
resolve(res);
console.log('压缩后体积', res.size / (1024 * 1024));
})
.catch((error) => {
reject(error);
});
});
}

 

posted @ 2024-11-22 10:24  乌龙茶爱上柠檬汁  阅读(0)  评论(0编辑  收藏  举报