检查选定的图像尺寸,并在超出范围时发出警报

时间:2016-11-10 09:42:34

标签: javascript jquery

我有一个显示所选图像以及图像宽度和高度的功能。如果图像尺寸大于390x390,我想进行检查以提醒。我已经标记了我认为尺寸检查应该去的地方,我可能错了。但它无论如何都不起作用。

如果有人有时间,请看看我应该如何检查尺寸。

非常感谢你的时间。

我的剧本:

window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("image_field"),
elPreview = document.getElementById("preview2"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL

function readImage (file) {
  var reader = new FileReader();
  reader.addEventListener("load", function () {
    var image = new Image();
    image.addEventListener("load", function () {
      var imageInfo = '<br><br>Your selected file size is<br>  Display width ' +
      image.width + ', Display height ' + 
      image.height + ' ' + '';


      elPreview.appendChild( this );
      elPreview.insertAdjacentHTML("beforeend",  imageInfo +'<br>');
    });
    image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
    if (useBlob) {
      window.URL.revokeObjectURL(file); 
    }
  });
  reader.readAsDataURL(file);
}

elBrowse.addEventListener("change", function() {
  var files = this.files;
  var errors = "";
  if (!files) {
    errors += "File upload not supported by your browser.";
  }
  if (files && files[0]) {
    for(var i=0; i<files.length; i++) {
      var file = files[i];
      if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
        readImage( file );
      } else {
        errors += file.name +" Unsupported Image extension\n";  
      }

      // SOMETHING LIKE THIS 
      if( (image.width < 390 && image.height < 390) .test(file.name) ) {

        readImage( file ); 
      } else {
        errors += file.name +" Selected image is to small\n";  
      }
      // END
    }
  }
  if (errors) {
    alert(errors); 
  }
});

3 个答案:

答案 0 :(得分:1)

我不确定我是否明白这个问题,但你的意思是这样吗?

elBrowse.addEventListener("change", function() {
var files  = this.files;
var errors = "";
if (!files) {
  errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
  for(var i=0; i<files.length; i++) {
  var file = files[i];
  if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
    if(image.width <= 390 && image.height <= 390)
    {
        readImage( file ); 
    } else {
        errors += file.name +" Selected image is to big\n";  
    }
  } else {
    errors += file.name +" Unsupported Image extension\n";  
  }

  }
}
if (errors) {
 alert(errors); 
}
});

答案 1 :(得分:1)

所以你需要将检查移动到事件监听器,因为这是你可以知道图像分辨率的第一个地方 在这里你没有错误列表,所以你需要稍微修改它,但你可以从这里开始:

window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("image_field"),
elPreview = document.getElementById("preview2"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL

function readImage (file) {

  var reader = new FileReader();
  reader.addEventListener("load", function () {
    var image = new Image();

    image.addEventListener("load", function () {
        if(image.width <= 390 && image.height <= 390)
        {
        var imageInfo = '<br><br>Your selected file size is<br>  Display width ' +
        image.width + ', Display height ' + 
        image.height + ' ' + '';


        elPreview.appendChild( this );
        elPreview.insertAdjacentHTML("beforeend",  imageInfo +'<br>');
        } else {
             alert ( file.name +" Selected image is to big\n");  
        }
    });
    image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
    if (useBlob) {
      window.URL.revokeObjectURL(file); 
    }
  });
  reader.readAsDataURL(file);
}

elPreview.addEventListener("change", function() {
var files  = this.files;
var errors = "";
if (!files) {
  errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
  for(var i=0; i<files.length; i++) {
  var file = files[i];
  if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {

        readImage( file ); 

  } else {
    errors += file.name +" Unsupported Image extension\n";  
  }

  }
}
if (errors) {
 alert(errors); 
}
});

对于文件变量(在您首先要检查尺寸的位置,您只能根据文件大小来确定条件 - 以字节为单位)

答案 2 :(得分:0)

加载图像并获取维度是异步的,所以你不能在for循环中使用检查,它在回调中完成了
(除非你使用async / await或generator + yield)

var elBrowse = document.getElementById('image_field')
var elPreview = document.getElementById('preview2')

// No point in addthing the listener if we can't read them anyway
if ('files' in elBrowse) {
  // No need for addEventListener if you only going to have 1 listener
  elBrowse.onchange = () => {
    for (let file of elBrowse.files) {
      file.image().then(image => {
        
        // Now if you don't like the extension you can always transform it
        // using the canvas element...

        if (image.width < 390 && image.height < 390)
          return console.error(file.name + ' is to small\n')

        let info = `<br><br>${file.name} size is ${file.size} bytes
        and dimension is ${image.width}x${image.height}<br>`

        elPreview.appendChild(image)
        elPreview.insertAdjacentHTML('beforeend', info)

      }, err => {
        console.error(file.name + " Isn't an image")
      })
    }
  }
} else {
  console.info('reading the file is not possible, use flash alternetive?')
}
<!-- 
Getting a bit of help from Screw-FileReader
ref: https://github.com/jimmywarting/Screw-FileReader
-->
<script src="https://cdn.rawgit.com/jimmywarting/Screw-FileReader/master/index.js"></script>

<!-- 
use the accept attribute to say that you only want images
So you don't have to check for it in your code
But for just in case we listen for image.onerror when we load the image 
-->
<input id=image_field type=file multiple accept="image/*">

<div id=preview2>