开发者

Image from URL then crop

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 !';
            }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜