vue3 对图片进行压缩

 

<upload-load ref="uploadLoadFile" 
@fileRowFunc="fileRowFunc"  
:uploadAttrs="{drag:true,'auto-upload':false}" 
tipText="" accept=".pdf, .doc, .docx, .png, .jpg, .gif, .jpeg, .xlsx,.xls">
<template #options>
			<el-icon size="50">
						<UploadFilled  />
				</el-icon>
			</template>
</upload-load>

 1.点击上传按钮进行图片/文件上传,文件流并传入父组件

	/*
	 * @param 选择文件自动获取文件流文件
	 * @returns {uploadFile,uploadFiles}返回接口数据
	 * @emit 
	 * @method onChange 附件上传
	 */
	const onChange = (uploadFile,uploadFiles) =>{
		let rawList=[];
		if(uploadFiles.length){
			uploadFiles.forEach((item)=>{
				rawList.push(item.raw)
			})
		}
		emit('fileRowFunc',rawList)
	}

2.针对文件流进行base64进行转换  并且进行大小进行压缩,这里压缩针对 图片类型

	/*
	 * @author ken
	 * @version 1.0
	 * @param flistList  传入文件流数组对象
	 * @description fileRowFunc 接收文件组件传过来的文件流进行处理 (同时判断是否是图片类型,如果是图片类型 进行base64再次压缩)
	 */
	const fileRowFunc = (flistList)=>{
		   state.demand.files=[];
		   if(flistList.length){
			    let obj = null;
			   flistList.forEach(async (item)=>{
				   await other.base64(item).then((res) => {
					    let fileType = item.name.split('.').pop().toLowerCase();
						if(['png','jpg','gif'].includes(fileType)===-1){
							other.getDealImage(res,1000,function(data){
								state.demand.files.push({
									fileName: item.name,
									base64Str: data
								});
							})
						}else{
							state.demand.files.push({
								fileName: item.name,
								base64Str: res
							});
						}
			   })
		   })
		   console.log(state.demand.files)
	    }
	}

3.压缩和转换关键得代码 other.js

/**
 * @param {file}  
 * @returns {string} 转Base64文件
 */
export function getBase64(file) {
	return new Promise((resolve, reject) => {
		///FileReader类就是专门⽤来读⽂件的
		const reader = new FileReader();
		//开始读⽂件
		//readAsDataURL: dataurl它的本质就是图⽚的⼆进制数据,进⾏base64加密后形成的⼀个字符串,
		reader.readAsDataURL(file);
		// 成功和失败返回对应的信息,reader.result⼀个base64,可以直接使⽤
		reader.onload = () => resolve(reader.result);
		// 失败返回失败的信息
		reader.onerror = (error) => reject(error);
	});
}
/**
 * @param {base64url} 
 * @returns {string} // 获取文件得大小
 */
 export function calSize(base64url) {
  let str = base64url.replace('data:image/png;base64,', '');
  const equalIndex = str.indexOf('=');
  if(str.indexOf('=') > 0) {
    str = str.substring(0, equalIndex);
  }
  const strLength = str.length;
  const fileLength = strLength - (strLength / 8) * 2;
  // 返回单位为MB的大小
  return  (fileLength / (1024 * 1024)).toFixed(2);
}

/**
 * @param {path,w,callback} 
 * @returns {callback} // 通过canvas压缩base64图片 并压缩
 */
 export function dealImage(path, w=1000, callback){
   const newImage = new Image();
        let size=calSize(path);//获取mb大小 
		let quality = 0.52
		if(size<=1){//1 mb
			quality=0.9;
		} if(size>1){
			quality = 0.8
		}
		
      newImage.src = path;
      newImage.setAttribute("crossOrigin", 'Anonymous');    // url为外域时需要
      let imgWidth;
      let imgHeight;
      newImage.onload = function() {
        imgWidth = this.width;
        imgHeight = this.height;
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        if (Math.max(imgWidth, imgHeight) > w) {
          if (imgWidth > imgHeight) {
            canvas.width = w;
            canvas.height = w * imgHeight / imgWidth;
          } else {
            canvas.height = w;
            canvas.width = w * imgWidth / imgHeight;
          }
        } else {
          canvas.width = imgWidth;
          canvas.height = imgHeight;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
        const newBase64 = canvas.toDataURL("image/jpeg", quality);
        callback(newBase64);
      }
}

/**
 * 统一批量导出

 * @method getBase64 文件转base64
 * @method dealImage 压缩图片
 * @method calSize 获取图片大小
 */
const other = {
	base64: (file) => {
		return getBase64(file)
	},
	getDealImage:(path, w, callback)=>{
		return dealImage(path, w, callback)
	},
	getCalSize:(url)=>{
		return calSize(url)
	}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑色咖啡 Ken

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值