简体   繁体   English

如何获取表示为 Unit8Array 的图像的大小?

[英]How do I get the size of an image represented as a Unit8Array?

I have an array of bytes of the user's avatar picture.我有一个用户头像图片的字节数组。 It represented as typed Unit8Array()它表示为类型化Unit8Array()

const imageBytes = new Unit8Array(...);

Now I need to check the image size for setting some limitations to prevent the user from putting massive images, but I can't come up with the idea how to calculate the image size.现在我需要检查图像大小以设置一些限制以防止用户放置大量图像,但我无法想出如何计算图像大小的想法。

How do I write this function?我该如何写这个 function? I need to get the image size in MB我需要以 MB 为单位获取图像大小

const getImageSizeInMB = unit8Array => { ... };

You've said the array contains the image data, so you already know the size of the image data: It's the size of the array.您已经说过数组包含图像数据,所以您已经知道图像数据的大小:它是数组的大小。 Since it's a Uint8Array , its length tells you how many 8-bit bytes it contains.由于它是一个Uint8Array ,它的length告诉你它包含多少个 8 位字节。 To get the size in megabytes, divide that number by 1024² (1,048,576) or 1000² (1,000,000) depending whether you mean megabyte in the sense many people often use it (1024²) or in the more technically-accurate-per-SI-terminology (where "mega" specifically means one million [1000²]).要获得以兆字节为单位的大小,请将该数字除以 1024² (1,048,576) 或 1000² (1,000,000),具体取决于您是指许多人经常使用的兆字节(1024²) 还是在技术上更准确的每 SI 术语 (其中“mega”特指一百万 [1000²])。 (If using "megabyte" to mean "one million," the term for 1024² is " mebibyte .") (如果使用“兆字节”来表示“一百万”,则1024²的术语是“兆字节”。)

const sizeInMB = uint8Array.length / 1_048_576;
// or
const sizeInMB = uint8Array.length / 1_000_000;

If the data were in a Uint16Array or Uint32Array or other array type that holds elements that are larger than an 8-bit byte, you'd use the byteLength property:如果数据位于Uint16ArrayUint32Array或其他包含大于 8 位字节的元素的数组类型中,则可以使用byteLength属性:

const sizeInMB = theArray.byteLength / 1_048_576;
// or
const sizeInMB = theArray.byteLength / 1_000_000;

(There's no reason you can't do that with your Uint8Array as well, for robustness; on Uint8Array and Int8Array , length and byteLength return the same values.) (没有理由你也不能用你的Uint8Array来做这件事,为了健壮性;在Uint8ArrayInt8Array上, lengthbyteLength返回相同的值。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM