繁体   English   中英

如何使用js / jquery加载图像大小(内存)

[英]How to get the image size (memory) after it is loaded using js/jquery

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

根据@CMS回答通过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获取图像数据?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM