I want to compress a base64 image to 100px and then smoothen it to make it look better.
I understand that imageSmoothingQuality does not work in firefox.
With the help of ChatGPT I have written a method to manipulate the pixels of the image directly to achieve a smoothing effect.
For some reason the smoothing works in chrome but not in firefox. Any idea why?
//this function compresses a base64 image to a given max height and width, it also keeps the aspect ratio
// if the given size is 100px it will also smoothen the pixels of the image to make it look better
compressImage(image: string, size: number) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = image;
var MAX_WIDTH = size;
var MAX_HEIGHT = size;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
if (size === 100) {
// this smoothes the pixels of the image to make it look better
// ctx!.imageSmoothingEnabled = true;
// ctx!.imageSmoothingQuality = 'high';
//imageSmoothingQuality is not supported in firefox, so we use the following code to smooth the image. The results are identical!
// for unknown reasons the following code alsoe doesn't work in firefox :(
// Get the pixel data of the image on the canvas
var imageData = ctx?.getImageData(0, 0, canvas.width, canvas.height);
// Manipulate the pixel data to smooth the image
// Loop through the rows of pixels in the image
if (imageData != null) {
for (var y = 0; y < imageData.height; y++) {
// Loop through the columns of pixels in the image
for (var x = 0; x < imageData.width; x++) {
// Get the index of the current pixel in the pixel data array
var index = (y * imageData.width + x) * 4;
// Get the red, green, blue, and alpha values of the current pixel
var r = imageData.data[index];
var g = imageData.data[index + 1];
var b = imageData.data[index + 2];
var a = imageData.data[index + 3];
// Calculate the average of the red, green, and blue values
var avg = (r + g + b) / 3;
// Set the red, green, and blue values of the current pixel to the average value
imageData.data[index] = avg;
imageData.data[index + 1] = avg;
imageData.data[index + 2] = avg;
}
}
// Draw the modified pixel data back onto the canvas
ctx!.putImageData(imageData, 0, 0);
}
}
ctx?.drawImage(img, 0, 0, width, height);
return canvas.toDataURL('image/png');
}