如何从画布中查找图像文件的大小

How to find size of an image file from canvas?

本文关键字:文件 图像 查找 布中      更新时间:2023-09-26

这里有一个调整jpeg image大小的js函数。函数将原始image的大小调整为width x heightalert中的image.size返回undefinedmainCanvas.toDataURL.length是调整大小的图像文件的大小吗?如果没有,调整大小后如何查找图像文件大小?

    function resize(image, width, height) {
      var mainCanvas = document.createElement("canvas");
      mainCanvas.width = width;
      mainCanvas.height = height;
      var ctx = mainCanvas.getContext("2d");
      ctx.drawImage(image, 0, 0, width, height);
      $('#uploaded_file_hidden_file').val(mainCanvas.toDataURL("image/jpeg")); 
      $('#file_size').val(Math.ceil(image.size/1024));
      alert(image.size);
    };

如果您所说的size是指以字节为单位的文件大小,则image元素将不具有类似image.size的size属性。你需要将画布转换成一个斑点,然后你就可以得到大小:

 // canvas.toBlob() is not well supported, so here is the polyfill just in case.
 // https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#Polyfill
 if (!HTMLCanvasElement.prototype.toBlob) {
 Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
  value: function (callback, type, quality) {
    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
        len = binStr.length,
        arr = new Uint8Array(len);
    for (var i=0; i<len; i++ ) {
     arr[i] = binStr.charCodeAt(i);
    }
    callback( new Blob( [arr], {type: type || 'image/png'} ) );
  }
 });
}
function resize(image, width, height) {
  var mainCanvas = document.createElement("canvas");
  mainCanvas.width = width;
  mainCanvas.height = height;
  var ctx = mainCanvas.getContext("2d");
  ctx.drawImage(image, 0, 0, width, height);
  $('#uploaded_file_hidden_file').val(mainCanvas.toDataURL("image/jpeg"));
  // Canvas to blob so we can get size.
  mainCanvas.toBlob(function(blob) {
    $('#file_size').val(Math.ceil(blob.size/1024));
    alert(blob.size);
  }, 'image/jpeg', 1);
};

要找出文件的最终大小,当然这是可能的,请检查包含指定格式的图像表示的数据URI的长度

  const imageFileSize = Math.round(mainCanvas.toDataURL('image/jpeg').length);