Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

imagecreatefromstring changes image color

Tags:

php

gd

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?

like image 476
Émile Perron Avatar asked Jun 16 '19 21:06

Émile Perron


1 Answers

This issue might be related to color profiles as GD does not seem to have support for color profiles. This might happen if for example your images are in the Adobe RGB colorspace which has more color information than sRGB. Here's some more information on the subject:

https://devot-ee.com/add-ons/support/ce-image/viewthread/1085

A possible solution is to use Photoshop to convert the image to sRGB (there's a "convert to sRGB" checkbox when exporting).

If that's not a possibility you can use ImageMagick instead of GD, which (as mentioned in the above link) does support color profiles.

like image 142
Ismael Padilla Avatar answered Oct 07 '22 11:10

Ismael Padilla