[英]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.