php - Resizing with GD outputs black images -
what can cause php gd produce black image after resizing? following code outputs black image 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] => 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. related os, installed packages, libraries, etc?
just tried reproduce situation. running code out-of-the-box php , apache displays following
the image “
http://localhost/” cannot displayed because contains errors.
although browser tells there errors, cannot seen because of headers returned in response of content-type: image/jpeg forcing browser interpret image. removing header , setting following output errors.
ini_set('error_reporting', e_all); ini_set('display_errors', true); ... //header('content-type: image/jpeg'); ... answer what can cause php gd produce black image after resizing?
since gd_info output proves gd extension loaded, check if filename (linux casesensitive) , permissions correct. if apache running www-data (group)
sudo chown :www-data test.jpg && sudo chmod 660 test.jpg code improvement / solution ini_set('error_reporting', e_all); ini_set('display_errors', true); if (extension_loaded('gd') && function_exists('gd_info')) { $filename = 'test.jpg'; if (file_exists($filename) && is_readable($filename)) { $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); } else { trigger_error('file or permission problems'); } } else { trigger_error('gd extension not loaded'); } comments this should used temporary solution (development environment). imho, errors should handled central error handler, display_errors should false in production. also, errors (in case there fatal error) logged default - check logs more (the frequent, better). also, on linux (with apt) one-liner install gd on system:
sudo apt-get update && sudo apt-get install php5-gd && sudo /etc/init.d/apache2 restart
Comments
Post a Comment