Search code examples
javascriptimagebytebuffer

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

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

Solution

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