Magento resize() image quality: dirty white background

digiwig picture digiwig · Dec 5, 2011 · Viewed 19.9k times · Source

I have a client who is seriously unhappy with the way their product thumbnails are rendering on Magento.

The dodgy appearance is noticeable on two accounts:

  • there is a dirty white background which has very light grey horizontal lines
  • and secondly there is ever so slight color loss (loses contrast and saturation).

I have removed ALL compression, set ALL quality to 100%, flushed image cache, experimented, broken, and fixed it all dozens of times, and nothing seems to work.

This version of Magento is ver. 1.4.2.0

Is anyone out here experiencing the same problems, and if so have you managed to fix it?

Answer

Jasuten picture Jasuten · Dec 6, 2011

The problem has to do with the php function imagecopyresampled in the resize function inside lib/Varien/Image/Adapter/Gd2.php, there are some rounding issues that occur to make a smoothly resized image.

My solution is to simply change any very light grey pixels in the image to pure white after the image has been resized. To do so first copy lib/Varien/Image/Adapter/Gd2.php to app/code/local/Varien/Image/Adapter/Gd2.php

Next find the following code inside the resize function (around line 312)

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

Then add the following code underneath:

// Clean noise on white background images
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);
            }
        }
    }
}

Flush the images cache from the Cache management in Magento, and you should have nicer images for the new displays. Few things to note when implementing this, there is a small performance hit the first time you generate the images again, and images with shadows may have sharper edges as the very light greys have been removed.