如何在JavaScript中检查高度和宽度图像

how to check height and width image in javascript

本文关键字:图像 高度 检查 JavaScript      更新时间:2024-01-02

如何在javascript中检查高度和宽度图像?

我的代码是:

jQuery.validator.addMethod('allowdimensions', function (value, element, params) {
    if (element.files.length < 1) {
        // No files selected
        return true;
    }
    if (!element.files || !element.files[0].size) {
        // This browser doesn't support the HTML5 API
        return true;
    }
    var minWidth = parseInt(params['minwidth'], 10);
    var maxWidth = parseInt(params['maxwidth'], 10);
    var minHeight = parseInt(params['minheight'], 10);
    var maxHeight = parseInt(params['maxheight'], 10);
    var image = {
        width: 0,
        height: 0
    };
    var reader = new FileReader();
    var img = new Image();
    reader.addEventListener("load", function () {
        img.src = reader.result;
    }, false);
    reader.readAsDataURL(element.files[0]);
    return image.width >= minWidth &&
        image.width <= maxWidth &&
        image.height >= minHeight &&
        image.height <= maxHeight;
});

image.widthimage.height总是0;要读取图像,会出现延迟。我不知道如何在返回输出之前读取图像。

尝试这样做。

reader.onload = function (e)
{
image.src = e.target.result;
image.onload = function ()
{
      // access image size here 
      if (this.width < 100 && this.height < 100)
      {
       // alert("To Small Image or your message"); 
      }
  }
}

Punit 答案是正确的。但是如果你使用的是jQuery,你可以使用这个:

$('#image_id').load(function(){
    var Img_Width = $(this).width();
    var Img_Height = $(this).height();
});

您的宽度和高度为 0,因为图像可能尚未加载到浏览器中。

我对你在这里想做什么有点困惑。但是试试这个:https://jsfiddle.net/3dqnc1wa/1/

j查询:

$("document").ready(function() {
  var imageWidth = $("img").width();
  var imageHeight = $("img").height();
  $("#dims").html("Width: " + imageWidth + " x Height: " + imageHeight)
  if(imageWidth >= 400 && imageHeight >= 200) {
    $("#test").html("It's equal to or wider than 400px and equal to or higher than 200px");
  } else if(imageWidth <= 399 && imageHeight <= 199) {
    $("#test").html("It's smaller than or equal to 399px wide and shorter than of equal to 199px");
  }
;});

.HTML:

<img src="http://placehold.it/350x150">
<div id="dims">
</div>
<div id="test">
</div>

我使用了.width().height()并将它们存储在变量(imageWidth/imageHeight(中,然后用一些条件检查它们。

你需要为 img 编写一个小的 onload 函数,以获得图像的宽度和高度,然后你可以相应地操作它。

var reader  = new FileReader();
  var img = new Image();
  reader.addEventListener("load", function () {
    preview.src = reader.result;
    img.src=reader.result;
  }, false);
    reader.readAsDataURL(file);
  img.onload = function() {
  //alert(this.width + 'x' + this.height);
  image.width=this.width;
  image.height=this.height;
}

宽度是图像的宽度,这个.高度是高度。AFter u 获取图像的高度和宽度,将其存储在图像 json 中,并将它们与最大高度和最大宽度、最小高度和最小宽度进行比较。

这是小提琴https://jsfiddle.net/AnonymousKB07/kn0h5tm2/3/希望这有帮助。