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:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With