IOS html5 upload picture direction problem solution

  • 2020-05-14 04:52:29
  • OfStack

If you use html5 to edit pictures and upload them, you may encounter the problem of the wrong direction of pictures on iphone mobile phone. Here, I would like to share the solution with you.
FileReader and Canvas of html5 have been used. For those of you who have not been exposed to html5, please first understand the method of FileReader and Canvas.


 // The method for file input Elements of the change The event 
 function change(){
  var file = this.files[0];
  var orientation;
  //EXIF js  The meta information of the image can be read  https://github.com/exif-js/exif-js
  EXIF.getData(file,function(){
    orientation=EXIF.getTag(this,'Orientation');
  });
  var reader = new FileReader();
  reader.onload = function(e) {  
    getImgData(this.result,orientation,function(data){
      // You can use the corrected image here data the  
    }); 
  }
  reader.readAsDataURL(file);
}


// @param {string} img  The image base64
// @param {int} dir exif Obtain directional information 
// @param {function} next  A callback method that returns the direction of correction base64
function getImgData(img,dir,next){
 var image=new Image();
 image.onload=function(){
  var degree=0,drawWidth,drawHeight,width,height;
  drawWidth=this.naturalWidth;
  drawHeight=this.naturalHeight;
  // The following changes 1 Next picture size 
  var maxSide = Math.max(drawWidth, drawHeight);
  if (maxSide > 1024) {
    var minSide = Math.min(drawWidth, drawHeight);
    minSide = minSide / maxSide * 1024;
    maxSide = 1024;
    if (drawWidth > drawHeight) {
      drawWidth = maxSide;
      drawHeight = minSide;
    } else {
      drawWidth = minSide;
      drawHeight = maxSide;
    }
  }
  var canvas=document.createElement('canvas');
  canvas.width=width=drawWidth;
  canvas.height=height=drawHeight; 
  var context=canvas.getContext('2d');
  // Determine image orientation and reset canvas Size, determine the rotation Angle, iphone The default is home Key on the right side of the landscape shooting mode 
  switch(dir){
    //iphone Landscape, right now home Button on the left side 
    case 3:
      degree=180;
      drawWidth=-width;
      drawHeight=-height;
      break;
    //iphone Portrait, at this point home Button below ( The normal direction to hold the phone )
    case 6:
      canvas.width=height;
      canvas.height=width; 
      degree=90;
      drawWidth=width;
      drawHeight=-height;
      break;
    //iphone Portrait, at this point home Button at the top 
    case 8:
      canvas.width=height;
      canvas.height=width; 
      degree=270;
      drawWidth=-width;
      drawHeight=height;
      break;
  }
  // use canvas Rotation correction 
  context.rotate(degree*Math.PI/180);
  context.drawImage(this,0,0,drawWidth,drawHeight);
  // Back to corrected picture 
  next(canvas.toDataURL("image/jpeg",.8));
 }
 image.src=img;
}

Related articles: