vue3 对图片进行压缩

 



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

你可能感兴趣的:(vue.js,javascript,前端)