How to draw photo with correct orientation in canvas after capture photo by using input[type='file'] in mobile web browser?

后端 未结 5 1474
青春惊慌失措
青春惊慌失措 2020-12-07 08:33

I am making a simple web app in mobile which allow visitor to capture photo by using html5 input[type=file] element. Then I will display it on the web for preview, and then

5条回答
  •  青春惊慌失措
    2020-12-07 09:18

    add exif.js to your project, then:

    EXIF.getData(file,function() {
      var orientation = EXIF.getTag(this,"Orientation");
      var can = document.createElement("canvas");
      var ctx = can.getContext('2d');
      var thisImage = new Image;
      thisImage.onload = function() {
        can.width  = thisImage.width;
        can.height = thisImage.height;
        ctx.save();
        var width  = can.width;  var styleWidth  = can.style.width;
        var height = can.height; var styleHeight = can.style.height;
        if (orientation) {
          if (orientation > 4) {
            can.width  = height; can.style.width  = styleHeight;
            can.height = width;  can.style.height = styleWidth;
          }
          switch (orientation) {
          case 2: ctx.translate(width, 0);     ctx.scale(-1,1); break;
          case 3: ctx.translate(width,height); ctx.rotate(Math.PI); break;
          case 4: ctx.translate(0,height);     ctx.scale(1,-1); break;
          case 5: ctx.rotate(0.5 * Math.PI);   ctx.scale(1,-1); break;
          case 6: ctx.rotate(0.5 * Math.PI);   ctx.translate(0,-height); break;
          case 7: ctx.rotate(0.5 * Math.PI);   ctx.translate(width,-height); ctx.scale(-1,1); break;
          case 8: ctx.rotate(-0.5 * Math.PI);  ctx.translate(-width,0); break;
          }
        }
    
        ctx.drawImage(thisImage,0,0);
        ctx.restore();
        var dataURL = can.toDataURL();
    
        // at this point you can save the image away to your back-end using 'dataURL'
      }
    
      // now trigger the onload function by setting the src to your HTML5 file object (called 'file' here)
      thisImage.src = URL.createObjectURL(file);
    
    });
    

    The orientation block (using translate and rotate) is copied from https://github.com/blueimp/JavaScript-Load-Image/blob/master/js/load-image-orientation.js and so I consider it well proven. It certainly worked perfectly for me, whereas other approaches didn't.

提交回复
热议问题