700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 解决上传图片自动旋转的问题以及对图片进行压缩上传

解决上传图片自动旋转的问题以及对图片进行压缩上传

时间:2020-05-03 03:52:53

相关推荐

解决上传图片自动旋转的问题以及对图片进行压缩上传

1. 关于图片自动旋转原因

在使用PS或者其他软件旋转图片时,图片旋转了,但Orientation不会改变,由于我们使用的图片预览器能够预处理图片,使其看起来与旋转后一致,但上传图片时,浏览器并不会预处理。所以导致图片旋转。

EXIF中,包含一个Orientation参数,用来记录拍摄照片时的方向,其中1是正常。

2. 解决旋转问题,需引入exif.js文件下载链接Exif.js 读取图像的元数据 - 前端开发仓库

顺带对图片进行压缩上传

// 1.图片旋转及图片压缩 fileObj指input上传的图片文件,callback会将base64图片传入,自行处理显示function compress(fileObj,callback) { if(typeof (FileReader) === 'undefined'){console.log("当前浏览器内核不支持base64图片压缩")// getObjectURL()方法见下方,无法压缩图片时直接将fileObj处理为网页可显示的图片callback(getObjectURL(fileObj))}else{try{var reader = new FileReader();reader.onload = function (e) {var image = new Image();image.onload = function () {var OrientationEXIF.getData(image, function() {Orientation = EXIF.getTag(this, 'Orientation');});var canvas = document.createElement('canvas'),context = canvas.getContext('2d'),squareW = this.width, //定义画布大小,也就是图片压缩之后的像素squareH = this.height;if(Orientation == 3) {canvas.width = squareW;canvas.height = squareH;context.rotate(Math.PI);context.drawImage(image, 0, 0, -squareW, -squareH);} else if(Orientation == 8) {canvas.width = squareH;canvas.height = squareW;context.rotate(Math.PI * 3 / 2);context.drawImage(image, 0, 0, -squareW, squareH);} else if(Orientation == 6) {canvas.width = squareH;canvas.height = squareW;context.rotate(Math.PI / 2);context.drawImage(image, 0, 0, squareW, -squareH);} else {canvas.width = squareW;canvas.height = squareH;context.drawImage(image, 0, 0, squareW, squareH);}var data = canvas.toDataURL('image/jpeg')callback(data)}image.src = e.target.result};reader.readAsDataURL(fileObj);}catch (e) {console.log('压缩失败!')callback(getObjectURL(fileObj))}}}

// getObjectURL() 将file类型转化为可显示的图片function getObjectURL(file) {var url = null ;if (window.createObjectURL!=undefined) { // basicurl = window.createObjectURL(file) ;} else if (window.URL!=undefined) { // mozilla(firefox)url = window.URL.createObjectURL(file) ;} else if (window.webkitURL!=undefined) { // webkit or chromeurl = window.webkitURL.createObjectURL(file) ;}return url;}

//base64转file dataurl是base64地址,filename是图片的名字function dataURLtoFile(dataurl, filename) { 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 File([u8arr], filename, {type:mime});}

//base64转blob dataurl是base64地址function 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});}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。