drpkcwwav20524605 2011-07-01 15:22
浏览 41
已采纳

来自URL的图像然后裁剪

So I've been trying to grab an image from an external URL, crop it and then save it. I could copy and save it okay but it's the crop part that is troubling me. I can't figure out how to get an image resource from the CURL stuff (I'm no good with curl this is someone else's curl stuff).

I though it was this:

$img = imagecreatefromstring($image);
$crop = imagecreatetruecolor(8,8);
imagecopy ( $crop, $img, 0, 0, 8, 8, 8, 8);

But no luck there, saves a corrupt PNG. Here is the full code:

            $link = "urlhere";
        $path = './mcimages/faces/';

            $curl_handle=curl_init(urldecode($link));
            curl_setopt($curl_handle, CURLOPT_NOBODY, true);
            $result = curl_exec($curl_handle);
            $retcode = false;
            if($result !== false)
            {
                $status = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
                if($status == 200)
                    $retcode = true;
            }
            curl_close($curl_handle);

            if($retcode)
            {
                $curl_handle=curl_init();
                curl_setopt($curl_handle,CURLOPT_URL,urldecode($link));
                curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
                curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
                $image = curl_exec($curl_handle);
                curl_close($curl_handle);

                if($image !== false)
                {
                    $img = imagecreatefromstring($image);
                    $crop = imagecreatetruecolor(8,8);

                    imagecopy ( $crop, $img, 0, 0, 8, 8, 8, 8 );

                    if(strpos($link,"/") !== false)

                    {
                        $name = explode("/",$link);
                        $total = count($name);
                        $handle = fopen($path.$name[$total-1],"w") or die("Could not create : ".$path.rand()."_".$name[$total-1]);
                        if($handle !== false)
                        {
                            fwrite($handle,$crop);
                            fclose($handle);
                            echo 'The file has been successfully saved !';

                        }
                    }
                }
            } else {
                echo 'File not found !';
            }
  • 写回答

1条回答 默认 最新

  • dsfadsa08911 2011-07-01 15:39
    关注

    AFAIK, this is wrong:

    fwrite($handle,$crop);
    

    use

    imagejpeg($crop, 'output-file.jpg'); // or imagepng()
    

    Your $crop is a resource, not a binary string with image data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用