• js 压缩图片


    之前使用 exif-js 获取图片方向后 修改宽高,旋转canvas后 对图片进行压缩,总是出现纯黑色的图片,所以采用了此种方法。


    // base64 转 blob文件
    export const dataURLtoBlob = (dataurl) => {
    	var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    		bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    	while (n--) {
    		u8arr[n] = bstr.charCodeAt(n);
    	}
    	return new Blob([u8arr], { type: mime });
    }
    
    export const compressImg = (file) => {
    	return new Promise((resolve, reject) => {
    		const reader = new FileReader();
    		reader.readAsDataURL(file);
    		const name = file.name;
    		reader.onload = (e) => {
    			const dataURL = (e.target as any).result;
    			// 图片小于2M不压缩
    			if (file.size < Math.pow(1024, 2) * 2) {
    				console.log('图片小于2m 不进行压缩');
    				resolve({base64: dataURL, file: file});
    				return;
    			}
    			const img: any = new Image;
    			img.src = dataURL, img.onload = function () {
    				const w = img.width / 2, // 宽度 
    					h = img.height / 2,
    					cvs = document.createElement("canvas"),
    					o = cvs.getContext("2d");
    				cvs.setAttribute("width", w + ''), cvs.setAttribute("height", h + ''), o.drawImage(this, 0, 0, w, h);
    				const i = cvs.toDataURL("image/jpeg", 0.8); // 压缩质量为 0.8  数值越小 压缩的图片越模糊 取值区间为 0 - 1
    				const _file: any = dataURLtoBlob(i);
    				_file.name = name;
    				resolve({
    					base64: i,
    					file: _file
    				});
    			}
    		}
    
    	})
    
    }
    

      

  • 相关阅读:
    Django项目上线的准备工作
    Centos安装MySQL5.6并重置密码
    Centos7.4下安装Python3
    Django单表查询及其方法
    thinkphp 视图模型使用分析
    thinkphp 统计某个字段不重复数 总数
    表结构相同的表,且在同一数据库 数据复制
    crontab 定时任务 每过多少分钟执行
    js event事件
    shell 验证ip
  • 原文地址:https://www.cnblogs.com/MainActivity/p/13469387.html
Copyright © 2020-2023  润新知