I've come across an issue where the getImageData
function of an HTML canvas is returning incorrect byte values.
To illustrate, I created a 1x1 pixel image using the following Python code:
from PIL import Image
import numpy as np
a = np.array([[[12, 187, 146, 62]]], dtype=np.uint8)
Image.fromarray(a).save('image.png')
After converting the image to base64 to embed it in the code snippet below:
let image = document.createElement('img');
image.addEventListener('load', () => {
let canvas = document.createElement('canvas');
let ctx = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
let data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
document.body.innerHTML = data;
});
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGPg2T3JDgADyAGYmiSbAQAAAABJRU5ErkJggg==";
Interestingly, running this code snippet in Firefox results in 12,189,148,62
, while in Chromium it displays 12,185,144,62
. However, the original values should be 12,187,146,62
.
I'm puzzled by this discrepancy. Can anyone shed some light on this?