Resizing with GD outputs black images

前端 未结 4 1070
抹茶落季
抹茶落季 2021-01-17 07:35

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.



        
4条回答
  •  心在旅途
    2021-01-17 08:28

    Research

    Just tried to reproduce your situation. Running your code with out-of-the-box PHP and Apache displays the following

    The image “http://localhost/” cannot be displayed because it contains errors.

    Although browser tells you that there were some errors, they cannot be seen because of the headers returned in response were of Content-Type: image/jpeg thus forcing browser to interpret it as an image. By removing the header and setting the following will output errors.

    ini_set('error_reporting', E_ALL);
    ini_set('display_errors', true);
    ...
    //header('Content-Type: image/jpeg');
    ...
    
    Answer

    What can cause php gd to produce a black image after resizing?

    Since the gd_info output proves that the GD extension is loaded, check if the filename (linux is caseSensitive) and permissions are correct. If Apache is running as 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 be used as a temporary solution (development environment). IMHO, the errors should be handled by a central error handler, display_errors should be false in production. Also, the errors (in this case there would be Fatal error) are logged by default - check the logs for more (the frequent, the better). Also, on linux (with apt) the one-liner will install GD on your system:

    sudo apt-get update && sudo apt-get install php5-gd && sudo /etc/init.d/apache2 restart
    

提交回复
热议问题