0

I am using this answer to display the uploaded image in an img tag and also I am able to change the orientation of the image using the loadImage() mentioned in the answer.

My problem is that I am not able to replace the re-oriented image with the uploaded image in the input tag.

The image is not saved unless the form is submitted. So I am not able to do this in AJAX also. Any help is much appreciated.

$('img#image-pre').click(function(e) {
  var loadingImage = loadImage($('input#uploadform-file')[0].files[0], function(img) {
    var dataURI = img.toDataURL();
    document.getElementById("image-pre").src = img.toDataURL();
    $('input#uploadform-file')[0].files[0] = function(dataURI) { // create the new blob from the changed image.
      var binary = atob(dataURI.split(',')[1]);
      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {
        type: mimeString
      });
    };
  }, {
    orientation: or,
    maxWidth: 500,
    maxHeight: 300,
    minWidth: 100,
    minHeight: 50,
  });
  or = or <= 8 ? or + 1 : 1;
  console.log($('input#uploadform-file')[0].files[0]);
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Bej
  • 143
  • 3
  • 13
  • 1
    What is this: `$('input#uploadform-file')[0].files[0] = function(dataURI) {....}` supposed to do ? You're reassigning the first file of the input to a function. – Titus May 28 '19 at 10:58
  • @Titus I am trying to recreate the blob object from the changed Img src and save it to the input value again – Bej May 28 '19 at 11:00
  • May I ask why your not doing it server side? If your using C# theres libraries which can detect if the orientation is correct according to the meta data. – Martin M May 28 '19 at 11:20
  • @MartinM I'm not trying this on the server side, js is on the frontend only. I am using yii and not c#. The requirement is such that the user will upload the image and change its orientation if needed and then submits it. – Bej May 28 '19 at 11:32
  • @Bej I get that you were trying to do this client-side (frontend), I was just asking why you were doing so. But may I suggest that you let the user select a image, upload it, and then present it to the user so that the user can change the orientation of the image. When the user has selected the orientation, then you parse this information on to the server which then proceed to change the actual orientation of the image (server-side). – Martin M May 28 '19 at 12:01

1 Answers1

0

You may want to look at this: https://stackoverflow.com/a/20285053/1990724

You can parse the image to base64 string and then using ajax you could post the base64 string to the server. This could be done after you had the user orientate the image the correct way.

Martin M
  • 463
  • 8
  • 20