Search code examples
phpgdphp-imaginewideimage

imagerotate changes original image's color


I am encountering a very strange behavior when rotating images with PHP. The original image is being changed during the rotation. As an example, here are the side by side images. It's hard to see, but if you look closely, the white area surrounding the knife is being changed from #FFFFFF to #FDFDFD.

enter image description here

I am using imagerotate with no options specified, however, if I try the same thing with a black background color, I get a rotated image with black "fill", but the white part of the image is still changed from #FFFFFF to #FDFDFD. I am baffled. It's almost like PHP is "rounding" the colors.

enter image description here

original image: https://i.sstatic.net/cK6mg.jpg

rotated image: https://i.sstatic.net/1413E.jpg

edit:

here's my code

$img = imagecreatefromjpeg($localFile);
$img = imagerotate($img, 45, 0);
imagejpeg($img, '/tmp/a.jpg');

Solution

  • I got it! On the php doc for imagerotate (http://php.net/manual/en/function.imagerotate.php) I noticed

    "Note: This function is affected by the interpolation method set by imagesetinterpolation()."

    I then tried a few different interpolation algorithms. IMG_BELL seems to maintain white.

    <?php
    function LoadJpeg($imgname)
    {
        $im = imagecreatefromjpeg($imgname);
        imagesetinterpolation($im, IMG_BELL);
        $im = imagerotate($im, 45, 0);
        return $im;
    }
    
    $img = LoadJpeg('test.jpg');
    
    imagejpeg($img, 'C:\temp\a.jpg', 100);
    imagedestroy($img);