I'd like to convert a buffered image response, from a fetch request being made, to image data or pixel data, usually stored in a Unit8ClampedArray as demonstrated by the Canvas API. Being that I can convert the buffer to base64 and return a data URI which can be used to view the image, I believe it should be possible to accomplish my goal; however, I couldn't find anything online.
I expected the buffer response to be in the proper order, 4 array items per pixel: rgba; however, as I'm sure you can tell, it's not that easy.
This is the image data I'm referring to:
let imageData = new ImageData(100, 100);
console.log(imageData.data); // Uint8ClampedArray[40000]
console.log(imageData.data.length); // 40000
I was missing countless pixels, or perhaps they weren't in the correct order. The outcome was not what I wanted nor was it anything close to the image it was supposed to display.
Here's a piece of my code to help you better understand my troubles:
async drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) {
image = await RequestHandler.ajax(image, {
headers: {
"content-type": "image/png"
}
});
const imageData = new Uint8ClampedArray(image);
const pixels = [];
for (let i = 0; i in imageData; i += 4) {
const average = (imageData[i] + imageData[i + 1] + imageData[i + 2]) / 3;
if (average < 130) {
// black;
pixels.push(0);
} else if (average < 210) {
// gray #aaa
pixels.push(170);
} else {
// white
pixels.push(255);
}
}
}