[英]How to find size of an image file from canvas?
这是一个调整 jpeg image
大小的 js 函数。 原始image
被函数调整为width x height
。 alert
的image.size
返回undefined
。 mainCanvas.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);
};
如果按大小表示文件大小(以字节为单位),则图像元素将不会具有类似image.size
的 size 属性。 您需要将画布转换为 blob,然后才能获得大小:
// 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.