Home > OS >  RGB image strange format canvas
RGB image strange format canvas

Time:07-20

I'm using this piece of code to get an image and convert it back to an array of integers:

const imageToTensor = async (url) => {
    const myImage = new Image;
    myImage.src = url
    await myImage.decode();
    const w = myImage.width, h = myImage.height;
    const canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = h;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(myImage, 0, 0);
    return ctx.getImageData(0, 0, w, h);
}

however, I get back an array with a strange format... the image is 160x200, but I'm getting an array of length 160x200x4 and not x3 (thus there is an additional value for each pixel)

my question is then, is this value the alpha of RGBa? To give some context, those are the first 20 elements in the array:

0: 124
1: 158
2: 187
3: 255
4: 130
5: 163
6: 193
7: 255
8: 131
9: 164
10: 194
11: 255
12: 130
13: 163
14: 193
15: 255
16: 132
17: 165
18: 195
19: 255

I don't know if the last one is the alpha value, since is 255 always, and afaik, alpha is between 0 and 1... any help?

CodePudding user response:

It's alpha, the default pixel format of a canvas is RGBA. Alpha is also between 0 and 255, these values are UINT8, there is no floats.

  • Related