使用带有imagecopyresampled()的PHP在没有fopen的情况下裁剪图像

时间:2011-08-10 03:18:27

标签: php image-processing curl gd fopen

我正在尝试使用PHP和GD库裁剪和图像,似乎无法让裁剪工作。我想裁剪下图中的黑条,并将其调整为较小的尺寸(200 x 112)。

Image located here

以下是我的PHP代码。

<?
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();

?>

我收到以下错误:

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

当我使用$this->myImage参数取消注释这两个方法并使用$this->thumb参数注释这两个方法时,原始图像会正确显示,因此我认为问题出现在imagecopyresampled()。注意:我没有能力启用fopen,所以这就是我使用curl的原因。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

imagecopyresampled()中使用之前,您需要为目标创建图像资源。

imagecopyresampled()

之前添加此内容
$this->thumb = imagecreatetruecolor(200, 112);

更新

对于裁剪,您应该只看imagecopy()而不是imagecopyresampled()

请随意查看我的图像处理类,了解一些想法 - https://gist.github.com/880506