Php 用于保存图像的功能
我创建了一个带有两个输入参数的函数。1输入图像url,另一个基本上是字符串,这是图像的源名称。我尝试以这样的方式创建它,如果它无法获取图像,则返回默认图像路径。然而,如果它无法获得图像,这是可行的,但它有时无法工作,并创建基本上为空的图像文件,因此我的想法是,图像无法完全下载 我的代码如下Php 用于保存图像的功能,php,curl,save-image,Php,Curl,Save Image,我创建了一个带有两个输入参数的函数。1输入图像url,另一个基本上是字符串,这是图像的源名称。我尝试以这样的方式创建它,如果它无法获取图像,则返回默认图像路径。然而,如果它无法获得图像,这是可行的,但它有时无法工作,并创建基本上为空的图像文件,因此我的想法是,图像无法完全下载 我的代码如下 function saveIMG($img_link, $source){ $name = date("Y-m-d_H_i_s_") . mt_rand(1,999) . "_".$source.".jpg
function saveIMG($img_link, $source){
$name = date("Y-m-d_H_i_s_") . mt_rand(1,999) . "_".$source.".jpg";
$ch = curl_init($img_link);
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_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
if ($result === FALSE){ //curl_exec will return false on failure even with returntransfer on
$name = "images/news_default.jpg";
return $name;
}
else {
$fp = fopen("images/$source/$name", 'w');
fwrite($fp, $result);
curl_close($ch);
fclose($fp);
$name ="images/$source/$name";
return $name;
}
}
您是否知道如何确保只保存工作图像,而不是空图像,如果图像为空,请向我返回默认的新闻图像
希望我足够清楚。您可以使用getimagesize(“img”)并检查类型
谢谢,在使用getimagesize函数修改函数后,修复了我的问题
function saveIMG($img_link, $source){
$name = date("Y-m-d_H_i_s_") . mt_rand(1,999) . "_".$source.".jpg";
$ch = curl_init($img_link);
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_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
if ($result === FALSE){
$name = "images/news_default.jpg";
return $name;
}
else {
$fp = fopen("images/$source/$name", 'w');
fwrite($fp, $result);
curl_close($ch);
list($width, $height, $type, $attr) = getimagesize($_SERVER['DOCUMENT_ROOT'] . "/project/images/$source/$name");
if (empty($width)){
unlink('images/$source/$name');
$name = "images/news_default.jpg";
return $name;
}
if (!empty($width)){
$name ="images/$source/$name";
return $name;
}
fclose($fp);
}
}谢谢,我使用了您的函数以便能够测试它,它完成了我的工作。