2

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 come 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 => { ... };

1 Answers1

4

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Is 1048576 the number of bytes in one MB ? –  May 01 '21 at 11:54
  • 1
    @Snowman It's the number of bytes in what most people call a "[megabyte](https://en.wikipedia.org/wiki/Megabyte)," yes. However, there's another definition that says the number is a million (1,000,000), not 1,048,576, and that's the definition usually used in the sizes of mass storage devices. Some people believe that the term for 1,048,576 should be [mebibyte](https://en.wikipedia.org/wiki/Binary_prefix). – T.J. Crowder May 01 '21 at 12:00
  • Yes, sometimes it's really confusing. Some people say 1 GB = 1024 MB, others say 1 GB = 1000 MB. –  May 01 '21 at 12:07
  • 1
    Yeah. That's why the binary prefixes were invented. Sadly, though, it hasn't made anything more clear. If you say "megabyte," people still don't know for sure what you mean, and if you say "mebibyte" to try to be clear you mean 1024², people just stare at you blankly as they have no idea what you just said and are wondering whether you just pronounced "megabyte" wrong. :-D – T.J. Crowder May 01 '21 at 12:11