【问题标题】:How can I check image orientation in Angular before uploading image如何在上传图像之前检查 Angular 中的图像方向
【发布时间】:2019-01-09 15:17:34
【问题描述】:

我只想在我的网站上上传的图片必须是纵向或方形的,我不想裁剪图片,要上传的图片默认必须是纵向或方形我已经搜索了网站数量\数字方法使用但没有工作过

知道我正在尝试这种方法,但它也不起作用,因为它正在异步运行

如果在给定代码中给出横向图像,它会运行,如果不应该运行 hasError 必须为真,但不是因为如果条件在上述代码完成之前运行,我该怎么办

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

【问题讨论】:

  • 我相信img.onload函数必须在你设置img.src之前定义,试试吧。
  • 您的问题是您试图在图像完成加载之前访问hasError 的值。 img.onload 是异步的,这意味着您的其余代码将继续运行,然后在加载图像时,onload 函数将然后执行。您的问题与图像方向无关,因为您说当图像为横向时它正在输出true。

标签: javascript angular angular6


【解决方案1】:

我认为你应该创建一个函数并将你的图像验证移动到你的函数中,并使用回调来找出图像是否有错误。

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

【讨论】:

    猜你喜欢
    • 2011-10-21
    • 2014-10-29
    • 1970-01-01
    • 2018-03-14
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多