-1

I have this HTML code to allow a user to upload a picture on my hybrid iOS app:

<input type="file" accept="image/*">

When selected, the web view gives the user 2 options. 1. Take a new picture 2. Choose an existing picture.

When the users selects 'Choose an existing picture' everything works fine. But if the user selects 'Take a new picture', when it uploads to Firebase Storage, it somehow uploads sideways.

How can I fix this? This is not ideal, but is there a way to only allow an 'existing picture' option?

Here is my code that processes the image and shows it in a <img>.

function fileUploaded(files) {

  var file = files[0];
  var reader = new FileReader();

  reader.onload = function (e) {

    var img = document.createElement("img");
    img.src = e.target.result;

    img.onload = function () {

      var canvas = document.createElement("canvas");

      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0);
      canvas.width = 200;
      canvas.height = 200;
      var xStart = 0;
      var yStart = 0;
      var newHeight = 0;
      var newWidth = 0;
      var aspectRadio = img.height / img.width;

      if (img.height < img.width) {
        //horizontal
        aspectRadio = img.width / img.height;
        newHeight = 200;
        newWidth = aspectRadio * 200;
        xStart = -(newWidth - 200) / 2;
      } else {
        //vertical
        newWidth = 200;
        newHeight = aspectRadio * 200;
        yStart = -(newHeight - 200) / 2;
      }


      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, xStart, yStart, newWidth, newHeight);

      dataurl = canvas.toDataURL(file.type);
      document.getElementById('img_element').src = dataurl;


    }

  }
  reader.readAsDataURL(file);

}
nachshon f
  • 3,540
  • 7
  • 35
  • 67
  • Is the sideways upload consistent? If so, you could always reorient the image before upload. I realize that this is not an ideal solution, but if nothing else works then maybe this might. –  Apr 24 '18 at 19:08
  • Sometimes its upside down and sometimes sideways. I guess there is no way to know. – nachshon f Apr 24 '18 at 19:59

1 Answers1

-1

Are you displaying the image before uploading? You might want to do that to see if it is already rotated by iOS (similar issue here). As for a fix, this might be what you will want to use.

Edit:
My previous response was somewhat vague. To be more precise, you're having a problem with the EXIF orientation. Here is a JSFiddle that will show you the orientation of the image and how it looks as an <img/> vs. as a <canvas>. The fix previously mentioned is still the path you will probably want to take. You should be able to use the library to correctly orient the image in a <canvas>. Here is an example of that library in use. Hope this helps!

Bryan Massoth
  • 1,109
  • 6
  • 7