Wednesday, 19 June 2019

imagecreatefromstring changes image color

I'm having issues with image resizing in PHP; it seems like from the moment I load an image using imagecreatefromstring or imagecreatefrompng, the colors change and become faded.

I know I have to use imagecreatetruecolor to create the destination image, but I don't even get to this point.

Here's a few examples to explain the results I am getting:

// This results in a discolored / faded image
$image = imagecreatefrompng('/path/to/my/image.png');
header('Content-Type: image/png');
imagepng($image);
die();

// This also results in a discolored / faded image
$image = imagecreatefrompng('/path/to/my/image.png');
$info = getimagesize('/path/to/my/image.png');
$sourceWidth = $info[0];
$sourceHeight = $info[1];

$resizedImage = imagecreatetruecolor($sourceWidth, $sourceHeight);
imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $sourceWidth, $sourceHeight, $sourceWidth, $sourceHeight);

header('Content-Type: image/png');
imagepng($resizedImage);
die();

// Obviously, this works flawlessly.
header('Content-Type: image/png');
echo file_get_contents('/path/to/my/image.png');
die();

Here's an example of before and after: Original on the left, faded on the right

Obviously, I must be missing something, but I've looked at every SO question and answer I could find without finding any solution to my problem.

Have you ever had this issue? How should I go about doing this?



from imagecreatefromstring changes image color

No comments:

Post a Comment