最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How do I get the size of an image represented as a Unit8Array? - Stack Overflow

matteradmin6PV0评论

I have an array of bytes of the user's avatar picture. It represented as typed 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 e up with the idea how to calculate the image size.

How do I write this function? I need to get the image size in MB

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

I have an array of bytes of the user's avatar picture. It represented as typed 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 e up with the idea how to calculate the image size.

How do I write this function? I need to get the image size in MB

const getImageSizeInMB = unit8Array => { ... };
Share Improve this question asked May 1, 2021 at 11:44 user15307601user15307601
Add a ment  | 

1 Answer 1

Reset to default 5

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. 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²]). (If using "megabyte" to mean "one million," the term for 1024² is "mebibyte.")

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:

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.)

Post a comment

comment list (0)

  1. No comments so far