我正在使用SO thread中的以下代码,但输出的文件是损坏的PNG文件。我无法在任何图像编辑器中查看它。我试图抓取的图片可以在this direct link找到。
<?php
function getimg($url) {
$headers[] = 'Accept: image/gif, image/png, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
$imgurl = 'http://download.videos.framebase.io/5a94a14f-aca6-4fb0-abd3-f880966358ab/6bf94ebb-4712-4895-9c85-fb8d4a19d50c/8f8b778f-6335-4351-82e7-6f50fd7fdd06/1351620000000-000020/thumbs/00001.png';
if(file_exists($imgsave)){continue;}
$image = getimg($imgurl);
file_put_contents($imgsave,$image);
?>
我错过了什么?是我正在使用的标题吗?是文件吗?我尝试在浏览器中手动保存文件,并且我的图像编辑器可以正常加载。
任何想法都会非常感谢,谢谢! - 24x7
修改 我知道我把它标记为已解决,但第二个想法,我仍然无法查看服务器正在保存的PNG。以下是迄今为止的建议:
<?php
function grab_image($url){
echo $url;
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
$saveto = 'recent-image.png';
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
grab_image("http://download.videos.framebase.io/2acd363b-ab1f-4305-8f1c-c1eaa6ebcc2a/abb6a3b7-414c-461b-a84c-56032060575d/e3682943-6959-456d-89db-8cd96647ddd4/1351620000000-000020/thumbs/00001.png");
?>
我一遍又一遍地运行剧本,没有运气,再次,任何帮助将不胜感激。这是它输出的PNG的sample。谢谢你提前。
答案 0 :(得分:2)
你可以使用像
这样的普通功能function grab_image($url,$saveto){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
$saveto = "D:/test.png";
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
grab_image('http://download.videos.framebase.io/5a94a14f-aca6-4fb0-abd3-f880966358ab/6bf94ebb-4712-4895-9c85-fb8d4a19d50c/8f8b778f-6335-4351-82e7-6f50fd7fdd06/1351620000000-000020/thumbs/00001.png','');
并确保在php.ini中启用allow_url_fopen ..