上传图片时如何获取图片的宽度和高度 (JavaScript)

3

我在上传功能中遇到了获取图像的宽度高度的问题。

这是我目前的代码:

// internal function that creates an input element
var file=newElement("input",0,"");

// sets the input element as type file
file.type="file";
file.multiple="multiple";
file.name="photoupload[]";
file.accept="image/*";

file.onchange=function(e){
  // internal function that creates an image element
  var img=newElement("img",0,"");
  img.src=URL.createObjectURL(this);
  img.onload=function(){
   var cw=img.clientWidth;
   var ch=img.clientHeight;
   alert(cw);alert(ch);
  }
}
file.click();

不太确定该如何解决这个问题。需要帮助,谢谢。

1个回答

1

将onload交换到更改src之前,并使用宽度和高度。

必须在更改src之前存在onload。

我假设newElement是一个执行document.createElement的函数 - 如果它没有返回图像对象,则需要将onload移动到该函数中。

// internal function that creates an input element
var file=newElement("input",0,"");

// sets the input element as type file
file.type="file";
file.multiple="multiple";
file.name="photoupload[]";
file.accept="image/*";

file.onchange=function(e){
  // internal function that creates an image element
  var img=newElement("img",0,"");
  img.onload=function(){
   var cw=img.width;
   var ch=img.height;
   console.log(cw,ch);
  }
  img.src=URL.createObjectURL(this);
}
file.click();

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