我有此脚本,可从特定网站获取图像链接,因此创建了一个函数,可在其中传递网站的图像链接和源名称,该功能将用于将图像放置在其相应目录中。
但是有时此功能无法正常工作,它会随机保存图像,但是图像基本上是空的,因此它将只保存带有$ img_link中原始文件名的空文件,但无法显示实际图像。
在这种情况下,如果发生这种情况,我会尝试返回默认的图像路径。但是它没有这样做,并且如上所述返回了一个空图像。
function saveIMG($img_link, $source){
$name = basename($img_link); // gets basename of the file image.jpg
$name = date("Y-m-d_H_i_s_") . mt_rand(1,999) . "_" .$name;
if (!empty($img_link)){
$ch = curl_init($img_link);
$fp = fopen("images/$source/$name", 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);
$name ="images/$source/$name";
return $name;
}
else {
$name = "images/news_default.jpg";
return $name;
}
}
您是否有更好的主意,如何在无法获取图像时提出理由?
谢谢
最佳答案
file_get_content
始终是cURL的良好替代方案。
但是,如果您想/必须使用cURL:
$ch = curl_init("www.path.com/to/image.jpg");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //Return the transfer so it can be saved to a variable
$result = curl_exec($ch); //Save the transfer to a variable
if($result === FALSE){//curl_exec will return false on failure even with returntransfer on
//return? die? redirect? your choice.
}
$fp = fopen("name.jpg", 'w'); //Create the empty image. Extension does matter.
fwrite($fp, $result); //Write said contents to the above created file
fclose($fp); //Properly close the file
就是这样。经过测试,它可以正常工作。
关于php - 使用CURL保存图像,有时会保存空白图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29516856/