在上传图片之前,如何在Angular中检查图片方向

3

我希望上传到我的网站上的图片必须是纵向或正方形的,而且我不想裁剪图片。上传的图片必须默认为纵向或正方形,我已经搜索了许多网站和方法,但没有一个方法能够实现。

现在我正在尝试这种方法,但它也不起作用,因为它是异步运行的。

如果在给定的代码中提供横向图像,则它会运行,这是不应该发生的,因为hasError必须为true,但实际上不是,因为if条件在上面的代码完成之前就运行了。那我该怎么办呢?

 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){
       .... 
   }

2
我认为 img.onload 函数必须在设置 img.src 之前定义,尝试一下。 - Calvin Godfrey
你的问题在于你试图在图片加载完成之前访问hasError的值。img.onload是异步的,这意味着你的代码的其余部分将继续运行,然后当图片加载完成时,onload函数将随后执行。你的问题与图像方向无关,因为你说当图像是横向时它输出true - Reinstate Monica Cellio
1个回答

2

我认为你应该创建一个函数,将图像验证放入该函数中,并使用回调来确定图像是否存在错误。

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);
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接