【问题标题】:Image from URL then crop来自 URL 的图像然后裁剪
【发布时间】:2011-07-01 15:22:20
【问题描述】:

所以我一直在尝试从外部 URL 中获取图像,对其进行裁剪然后保存。我可以复制并保存它,但困扰我的是裁剪部分。我不知道如何从 CURL 的东西中获取图像资源(我不擅长 curl 这是别人的 curl 东西)。

我虽然是这样的:

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

但是没有运气,保存了损坏的 PNG。完整代码如下:

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

【问题讨论】:

    标签: php image curl png crop


    【解决方案1】:

    AFAIK,这是错误的:

    fwrite($handle,$crop);
    

    使用

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

    您的 $crop 是一种资源,而不是带有图像数据的二进制字符串。

    【讨论】:

    • 做到了。虽然 imagecopy 似乎试图通过平滑颜色来“修复”图像,就好像它正在调整大小一样,但我该如何阻止呢?#
    • 嗯,一定与从 jpg->PNG 开始有关。将 imagecreatetruecolor 更改为仅 imagecreate 并将其保存为 PNG,现在它很完美。负载也更小。 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2021-12-16
    • 2015-02-15
    • 2013-09-13
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    相关资源
    最近更新 更多