In some browsers such as firefox, when you upload an image to a page with a FileReader, the exact colors of the pixels in the image are incorrect. This is due to a known/ignored "bug" with firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1396587
It's loaded using a FileLoader:
const fileList = this.files;
const reader = new FileReader();
reader.onload = function () {
img.onload = ()=> {
//place image on canvas so we can getImageData
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
let img = $(".mapDataPreview");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
let pixel = ctx.getImageData(0, 0, 1, 1).data;
console.log('pixel data', pixel);
}
img .src = reader.result;
};
reader.readAsDataURL(mapDataFile);
If I load the image using chrome, it usually reads the colors correctly: the RGB values i get from getImageData() match the actual pixel values in the image file, if I open it in an image editor like photoshop or paint.
If I load the image in firefox, and it has a color profile attached (which is automatically placed there by some software), then occasionally the pixel colors will be slightly off, eg:
photoshop: #ff0000 | chrome: [255,0,0] | firefox: [254,0,0]
I frequently need to grab colors from images, and this causes a lot of problems where the color data I get from the browser does not match the image the user uploaded.
There is kind of a solution: If I use pngcrush on the image before uploading, it then shows proper colors when uploaded, even in firefox. (I assume that pngcrush discards these color profiles)
Unfortunately, I can not use pngcrush in the browser, and forcing people to use chrome to use my website is ridiculous.
Can anyone find a workaround/hack to avoid this bug, and get the actual pixel colors of the image a user uploads?