Cropping an image with imagecopyresampled() in PHP without fopen

拈花ヽ惹草 提交于 2019-12-11 11:04:41

问题


I am trying to crop and image using PHP and the GD library and cannot seem to get the cropping to work. I would like to crop the black bars out of the following image and resize it to a smaller size (200 by 112).

Image located here

Below is my PHP code.

<?
function load_file_from_url($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $str = curl_exec($curl);
    curl_close($curl);
    return $str;
}

class cropImage{
 var $imgSrc,$myImage,$thumb;
 function setImage($image) {
       //Your Image
         $this->imgSrc = $image; 

       //create image from the jpeg
         $this->myImage = imagecreatefromstring($this->imgSrc) or die("Error: Cannot find image!"); 
     imagecopyresampled($this->thumb, $this->myImage, 0, 0, 0, 45, 200, 112, 480, 270);       
    }
    function renderImage()
    {                            
         header('Content-type: image/jpeg');
         imagejpeg($this->thumb);
         imagedestroy($this->thumb); 
         //imagejpeg($this->myImage);
         //imagedestroy($this->myImage); 
    }
}  

    $image = new cropImage;
    $image->setImage(load_file_from_url($_GET['src']));
    $image->renderImage();

?>

I receive the following errors:

PHP Warning:  imagecopyresampled(): supplied argument is not a valid Image resource in /var/www/html/root/vic/boilerBytes/thumbnail.php on line 21
[Tue Aug 09 22:57:06 2011] [error] PHP Warning:  imagejpeg(): supplied argument is not a valid Image resource in /var/www/html/root/vic/boilerBytes/thumbnail.php on line 26
[Tue Aug 09 22:57:06 2011] [error] PHP Warning:  imagedestroy(): supplied argument is not a valid Image resource in /var/www/html/root/vic/boilerBytes/thumbnail.php on line 27

When I uncomment the two methods with $this->myImageparameters and comment the two methods with $this->thumbparameters, the original image properly displays, so I'm thinking the issue arises with imagecopyresampled(). Note: I do not have the ability to enable fopen, so this is why I'm using curl. Any help would be greatly appreciated!


回答1:


You need to create an image resource for the destination before using it in imagecopyresampled().

Add this before the imagecopyresampled() line

$this->thumb = imagecreatetruecolor(200, 112);

Update

For cropping, you should probably just look at imagecopy() instead of imagecopyresampled()

Feel free to have a look at my image manipulation class for some ideas - https://gist.github.com/880506



来源:https://stackoverflow.com/questions/7005501/cropping-an-image-with-imagecopyresampled-in-php-without-fopen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!