Search code examples
phpphp-gd

Remake images using imagecolorallocate (PHP) but getting different color


public function createNewImage222($image){
$image = imagecreatefromjpeg($image);
$width = imagesx($image);
$height = imagesy($image);
$img = imagecreatetruecolor($width,$height);
for ($x = 0; $x <$width; $x++)
{
    for ($y = 0; $y <$height ; $y++){
        $rgb = imagecolorat($image, $x, $y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;
        $color =  imagecolorallocate($img,$r,$g,$b);
        imagesetpixel($img,$x,$y,$color);
    }
}

$new_img = imagecreate($width,$height);
imagecopyresized($new_img,$img,0,0,0,0,$width,$height,$width,$height);
return $new_img;}

this my code and show the result use :

header('Content-Type: image/jpeg');
imagejpeg($result,null,100)
imagedestroy($result);

but getting different colors and size. original image 13KB and result 40KB. Sorry i can't post the images.


Solution

  • $new_img =  imagecreatetruecolor($width,$height);
    

    http://php.net/manual/en/function.imagecreate.php

    recommend the use of imagecreatetruecolor() instead of imagecreate()