javascript - 如何在使用js/jquery加载图像后获取图像大小(内存)

标签 javascript jquery html

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

最佳答案

根据@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);

据我所知,这是唯一可能的解决方案。

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

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));

来源:How can I estimate the disk size of a string with JavaScript? , Get image data in JavaScript?

关于javascript - 如何在使用js/jquery加载图像后获取图像大小(内存),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18333144/

相关文章:

javascript - three.js 使用颜色过渡动画网格 (tween.js)

jquery - 获取准确的元素高度

javascript - 更改标签以匹配 ID 中的数字部分

jquery - 如果单击子项,如何防止动画?

javascript - ng-bind-html 不能正常工作

javascript - Javascript 日期对象中的时间不同

jquery - 将 tbody 更新为 div 内容

html - 仅在一定深度内显示元素,直至展开

javascript - 在 href 点击上使用动画功能

javascript - 重构 javascript 以允许在不需要括号且不使用 'get' 的情况下调用函数