Reputation: 10350
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);
};
Upvotes: 1
Views: 3883
Reputation: 2017
To find out the final size of the file, which is of course possible, check the length of the data URI containing the image representation in the specified format
const imageFileSize = Math.round(mainCanvas.toDataURL('image/jpeg').length);
Upvotes: 1
Reputation: 1588
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);
};
Upvotes: 1