Background noise in Magento image resize

After getting new LED monitors I discovered that all the images with white backgrounds in the Magento sites I was making had an annoying background noise/artifacts. Since the noise is very close to white (#fefefe or #fdfdfd) most people with LCD monitors will not notice.

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
            $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.

If anyone has a better solution please leave a comment.

This entry was posted in Magento. Bookmark the permalink.

2 Responses to Background noise in Magento image resize

  1. Adrian says:

    Awesome fix. I’ve been trying to get rid of grey slats on isolated (white background) images since v1.3
    Many thanks.

  2. Millidge says:

    Works like a charm in
    I though my eyes were going, or there was a fault with my new LCD monitors.
    Thanks so much!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>