Magento image quality on resize – GD library white color loss

When magento resizes images, resized images always loss their original colors. whether you set quality to 100 or not. Maybe it’s okay to live with to some of us.

But what if it’s true color such as white(#FFF) or black(#000)? As far as I tested, GD2(magento default image lib) doesn’t really handle well with these. So if you really want to keep white color as white then you will need some update on magento’s GD2 file.

So here is the sample code for fixing white color issues.

this is how magento is resizing the image

 // resample source image and copy it into new frame
imagecopyresampled(
    $newImage,
    $this->_imageHandler,
    $dstX, $dstY,
    $srcX, $srcY,
    $dstWidth, $dstHeight,
    $this->_imageSrcWidth, $this->_imageSrcHeight
);

You will need to add below code to make stay white as white 🙂

if ($isTrueColor) {
    $colorWhite = imagecolorallocate($newImage,255,255,255);
    $processHeight = $dstHeight+$dstY;
    $processWidth = $dstWidth+$dstX;
    //Travel y axis
    for($y=$dstY; $y<($processHeight); ++$y){
        // Travel x axis
        for($x=$dstX; $x<($processWidth); ++$x){ // Change pixel color $colorat=imagecolorat($newImage, $x, $y); $r = ($colorat >> 16) & 0xFF;
        	$g = ($colorat >> 8) & 0xFF;
        	$b = $colorat & 0xFF;
        	if(($r==253 && $g == 253 && $b ==253) || ($r==254 && $g == 254 && $b ==254)) {
        		imagesetpixel($newImage, $x, $y, $colorWhite);
        	}
        }
    }
}