3

我想知道使用 js 或 jquery 如何在加载图像后获取图像的大小(字节、KB、MB)。我不想使用任何 ajax 或发送任何额外的 http 请求。就像我们使用 $("#imageId").height() 一样,我们如何获取内存大小?

4

1 回答 1

6

根据 @CMS 在Determining image file size + dimensions via Javascript 中的回答?

 var xhr = new XMLHttpRequest();
 xhr.open('HEAD', 'img/test.jpg', true);
 xhr.onreadystatechange = function(){
  if ( xhr.readyState == 4 ) {
   if ( xhr.status == 200 ) {
     alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
   } else {
     alert('ERROR');
   }
  }
 };
 xhr.send(null);

这是AFAIK唯一可能的解决方案。

更新: 我不知道这个解决方案有多准确,但这是我的猜测

function bytes(string) {
  var escaped_string = encodeURI(string);
  if (escaped_string.indexOf("%") != -1) {
    var count = escaped_string.split("%").length - 1;
    count = count == 0 ? 1 : count;
    count = count + (escaped_string.length - (count * 3));
  }
  else {
    count = escaped_string.length;
  }
}
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;

// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");

var base_64 = dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); 
console.log(bytes(base_64));

资料来源:如何使用 JavaScript 估计字符串的磁盘大小?,在 JavaScript 中获取图像数据?

于 2013-08-20T10:52:46.250 回答