【发布时间】: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 !';
}
【问题讨论】: