How can I check image orientation in Angular before uploading image

Viewed 773

I just want to image being upload on my website must portrait or square and I don't want to crop image, image to be uploaded must be portrait or square by default I have searched number of website \ number method use but none worked

know I am trying this method but it also not working because it is running async

if give landscape image in given code it runs if which should not run as hasError must be true but doesn't because if condition run before the above code could complete so what can I do

 let hasError = false;
 image = event.target.files[0];
    if (image) {
      var img = new Image();
      img.src = window.URL.createObjectURL(image);
      img.onload = function () {
        height = img.naturalHeight;
        width = img.naturalWidth;
        console.log(hasError);  // prints false
        if (height < width)  {
           hasError = true; // prints true 
           console.log(hasError);
        }
        window.URL.revokeObjectURL(img.src);
     }
    console.log(hasError); //prints flase
   }
   if(!hasError){
       .... 
   }
1 Answers

I think you should create a function and move your image validation into your function and use a callback to find out the image has error or not.

var fileInput = document.querySelector('input[type="file"]');
var preview = document.getElementById('preview'); //img tag

previewImage(function(hasError){
  if (!hasError){
    //do something
  }
});

function previewImage(callback){
  fileInput.addEventListener('change', function(e) {
    preview.onload = function() {
      
        height = this.naturalHeight;
        width = this.naturalWidth;
        if (height < width)  {
           callback(true);
        } 
        window.URL.revokeObjectURL(this.src);
        callback(false);
    };

    var url = URL.createObjectURL(e.target.files[0]);
    preview.setAttribute('src', url);
}, false);
}

Related