What can cause php gd to produce a black image after resizing? The following code always outputs a black image for every valid jpeg file.
<?php
$filename = 'test.jpg';
$percent = 0.5;
header('Content-Type: image/jpeg');
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb);
imagedestroy($thumb);
?>
output of gd_info()
:
Array
(
[GD Version] => bundled (2.1.0 compatible)
[FreeType Support] => 1
[FreeType Linkage] => with freetype
[T1Lib Support] =>
[GIF Read Support] => 1
[GIF Create Support] => 1
[JPEG Support] => 1
[PNG Support] => 1
[WBMP Support] => 1
[XPM Support] =>
[XBM Support] => 1
[JIS-mapped Japanese Font Support] =>
)
The code appeared working in other environments. Probably it is related to OS, installed packages, libraries, etc?
Just tried to reproduce your situation. Running your code with out-of-the-box PHP and Apache displays the following
Although browser tells you that there were some errors, they cannot be seen because of the headers returned in response were of
AnswerContent-Type: image/jpeg
thus forcing browser to interpret it as an image. By removing theheader
and setting the following will output errors.Since the
Code improvement / solution Commentsgd_info
output proves that the GD extension is loaded, check if the filename (linux is caseSensitive) and permissions are correct. IfApache
is running aswww-data
(group)This should be used as a temporary solution (development environment). IMHO, the errors should be handled by a central error handler,
display_errors
should befalse
in production. Also, the errors (in this case there would beFatal error
) are logged by default - check the logs for more (the frequent, the better). Also, on linux (withapt
) the one-liner will install GD on your system: