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

解决图片显示Exif.js改变图片显示方向

时间:2023-04-02 20:53:26 HTML

代码上直接没有文字//这是解决exif变化方向的js文件//应用前npminstallexif-js--save或者直接importexif-js////调用方法//让baseData;//imgExif(file,function(base){//baseData=base//});importExiffrom'exif-js'//引入exifletu={};//转换的主要方法u.index=(file,callback)=>{letOrientation,resultData;//图片的方向,返回值//获取拍照时的信息,解决图片旋转的问题Exif.getData(file,function(){Orientation=Exif.getTag(this,'方向');});//检查是否支持FileReaderif(!file||!window.FileReader)return;//检查是否支持FileReaderif(!file||!window.FileReader)return;if(/^image/.test(file.type)){//创建一个阅读器letreader=newFileReader();//将图像2转换为base64格式reader.readAsDataURL(file);//读取成功回调reader.onloadend=function(){letresult=this.result;//判断图片是否有方向值,不直接返回base64if(!Orientation){callback(result);}else{letimg=newImage();img.src=结果;//图片信息加载及转换方向img.onload=function(){resultData=u.compress(img,方向);回调(结果数据);}}}}};//改变旋转方向u.compress=(img,Orientation)=>{letcanvas=document.createElement("canvas"),ctx=canvas.getContext('2d'),tCanvas=document.createElement("canvas"),tctx=tCanvas.getContext("2d"),initSize=img.src.length,width=img.width,height=img.height,ratio=1;//声明canvas.width=width;canvas.height=高度;//设置背景色ctx.fillStyle="#fff";ctx.fillRect(0,0,canvas.width,canvas.height);//如果图片像素大于100万,则使用tile绘制letcount;if((count=width*height/1000000)>1){//console.log("超过100W像素");count=~~(Math.sqrt(count)+1);//计算要分成多少块//计算每个块的宽和高letnw=~~(width/count);让nh=~~(高度/计数);tCanvas.width=nw;tCanvas.height=nh;for(leti=0;i{//最小和最大旋转方向,图像旋转4次后回到原来的方向constmin_step=0;constmax_step=3;如果(img==null)返回;//img的高度和宽度不能在img元素隐藏后获取,否则会报错letheight=img.height;让width=img.width;让步骤=2;如果(步骤==空){step=min_step;}if(direction=='right'){step++;//旋转到原位置,即超过最大值step>max_step&&(step=min_step);}else{步骤--;步骤<最小步数&&(步骤=最大步数);}//旋转180度step=num?数量:步骤;//旋转角度参数化为弧度letdegree=step*90*Math.PI/180;让ctx=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:canvas.width=height;canvas.height=宽度;ctx.rotate(degree);ctx.drawImage(img,-width,0);休息;}};窗户。imgExif=u;如果后台需要该文件,请使用它进行转换。//将base64转换为img文件u.compress=(img,Orientation)=>{letarr=dataurl.split(','),mime=arr[0].match(/:(.*?);/)[1],bstr=atob(arr[1]),n=bstr.length,u8arr=newUint8Array(n);while(n--){u8arr[n]=bstr.charCodeAt(n);}returnnewFile([u8arr],文件名,{type:mime});};