Here is a js function resizing an jpeg image
. The original image
is resized to width x height
by the function. The image.size
in alert
returns undefined
. Is mainCanvas.toDataURL.length
the size of resized image file? If not, how to find the image file size after resizing?
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);
};
If by size you mean file size in bytes, the image element will not have a size property like image.size
. You would need to convert the canvas into a blob and then you can get the 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.