如何在 javascript 中获取 HTML5 Canvas.todataurl 文件大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18557497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:23:26  来源:igfitidea点击:

How to get HTML5 Canvas.todataurl file size in javascript?

javascripthtml5-canvas

提问by venkat7668

var data_url=canvas.toDataURL("image/png");

var data_url=canvas.toDataURL("image/png");

var img=$("#img").attr("src",data_url);

var img=$("#img").attr("src",data_url);

what is the imgfile size in kb?

什么是IMG以KB文件的大小?

回答by Pedro L.

If you want to know the size of the data-url in bytes you can do:

如果你想知道 data-url 的大小(以字节为单位),你可以这样做:

var imgFileSize = data_url.length;

var imgFileSize = data_url.length;

But that's not the real size of the png size. You can approximate very accurately to the real PNG size this way:

但这不是 png 大小的实际大小。您可以通过这种方式非常准确地近似到真实的 PNG 大小:

var head = 'data:image/png;base64,';
var imgFileSize = Math.round((data_url.length - head.length)*3/4) ;

Because the Base64 encoding has a 4/3 overhead.

因为 Base64 编码有 4/3 的开销。

Edit:corrected the size calculation after comments.

编辑:更正评论后的大小计算。

回答by Albert Still

Best way to think about it is that each char represents 6 bits (2^6== 64, hence the Base64). So times the amount of chars you have by 6 to get the total number of bits. Then divide the total number of bits by 8 to get the amount of bytes, because a byte is 8 bits.

考虑它的最佳方式是每个字符代表 6 位(2^ 6== 64,因此是 Base 64)。因此,将您拥有的字符数乘以 6 以获得总位数。然后将总位数除以 8 得到字节数,因为一个字节是 8 位。

Math.round(base64String.length * 6 / 8);

Math.round(base64String.length * 6 / 8);

Which is the same as Math.round(base64String.length * 3 / 4);.

这与Math.round(base64String.length * 3 / 4);.

回答by Kareem

base64 estimates will always vary!

base64 估计总是会有所不同!

Decode the base64 string and check its length. This method is always 100% accurate!

解码 base64 字符串并检查其长度。这个方法总是100%准确!

var content_without_mime = base64.split(",")[1];
var size_in_bytes = window.atob(content_without_mime).length;

回答by Endless

I didn't find that Pedro's solution accurate, what i did was to create a blob out of the canvas and then get the fileSize

我没有发现 Pedro 的解决方案准确,我所做的是从画布中创建一个 blob,然后获取文件大小

canvas.toBlob(function(blob){
    alert(blob.size);
});

canvas.toBlob is a working draft at this moment, but i used a pollyfill

canvas.toBlob 目前是一个工作草案,但我使用了pollyfill

i think canvas.mozGetAsFile could also work, but i haven't tested

我认为 canvas.mozGetAsFile 也可以工作,但我还没有测试