当前位置: 首页 > Web前端 > HTML5

网页端上传图片时,图片旋转了

时间:2023-04-05 16:52:51 HTML5

网页端上传图片有时会出现这种情况。前向图片在上传和预览时会旋转。发生这种情况是因为一张照片包含许多记录拍摄信息的属性。读取这些属性需要引入EXIF(可以在npm上搜索exif-js下载)。EXIF中包含一个Orientation参数,用于记录拍照时的方位。使用PS或其他软件旋转图片时,图片旋转了,但是Orientation不会改变,因为我们使用的图片预览器可以对图片进行预处理,使其看起来与旋转后的图片一致,但是上传图片时,浏览器不会进行预处理。所以图像被旋转了。要解这道题,必须要明白Orientation的含义,它一共有8个值,分别是:1、2、3、4、5、6、7、8。这8个值对应的含义是:方位解读1正常2正常镜子3顺时针旋转180°4顺时针旋转180°镜子5顺时针旋转270°镜子6顺时针旋转270°7顺时针旋转90°镜子8顺时针旋转90°。网上有一张图,可以更直观的清楚的看出对应关系。代码层面,引入exif-js后,可以获取照片的Orientation值。然后根据Orientation判断如何旋转照片。下面是一个例子EXIF.getData(file,function(){varOrientation=EXIF.getTag(this,"Orientation");console.log("Orientation>>>>>>",Orientation);//转换为base64constreader=newFileReader();reader.readAsDataURL(file);reader.onload=e=>{if(Orientation==1){console.log("图片不需要处理");}else{varuploadBase64=newImage();uploadBase64.src=e.target.result;uploadBase64.onload=function(){//修复图片旋转varexpectWidth=uploadBase64.width;varexpectHeight=uploadBase64.height;varcanvas=document.createElement("canvas"),ctx=canvas.getContext("2d");canvas.width=expectWidth;canvas.height=expectHeight;ctx.drawImage(uploadBase64,0,0,expectWidth,expectHeight);varbase64=空;如果(方向ion!==""&&Orientation!=1){switch(Orientation){case6:console.log("顺时针旋转270度");rotateImg(uploadBase64,"左",canvas);休息;case8:console.log("顺时针旋转90度");rotateImg(uploadBase64,"右",canvas);休息;case3:console.log("顺时针旋转180度");rotateImg(uploadBase64,“水平”,画布);休息;}//输出转换成base64的图片varbase64=canvas.toDataURL(file.type,1);//输出转换流varnewBlob=_this.convertBase64UrlToBlob(base64,file.type);}};}};})//旋转图像rotateImg(img,direction,canvas){console.log("开始旋转图片");//图片旋转4圈后返回原方向if(img==null)return;varheight=img.height;varwidth=img.width;可变步骤=2;if(direction=="right"){步骤++;}elseif(direction=="left"){步骤--;}elseif(direction=="horizen"){step=2;//没有处理}//旋转角度参数化为弧度vardegree=step*90*Math.PI/180;varctx=canvas.getContext("2d");switch(step){案例0:canvas.width=width;canvas.height=高度;ctx.drawImage(img,0,0);休息;案例一:canvas.width=height;canvas.height=宽度;ctx.rotate(degree);ctx.drawImage(img,0,-height);休息;情况2:canvas.width=width;canvas.height=高度;ctx.rotate(degree);ctx.drawImage(img,-width,-height);休息;案例3:画布as.width=height;canvas.height=宽度;ctx.rotate(degree);ctx.drawImage(img,-width,0);休息;}console.log("Endrotatingimage");}这样可以解决问题,网页端上传图片时,图片旋转了。