1

我创建了一个带有两个输入参数的函数。1输入图片url,另一个基本是字符串,就是图片的源名称。我试图以这样的方式创建它,如果它无法获取图像,则返回默认图像路径。但是,这在无法获取图像的情况下有效,但有时它不起作用并且创建基本上是空的图像文件,因此我的想法是图像无法完全下载。

我的代码如下。

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;
}
}

你知道如何确保只保存工作图像,而不是空图像,如果图像为空,则返回默认的新闻图像。

希望我足够清楚。

4

2 回答 2

1

谢谢,在使用 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);
}

}

于 2015-04-22T14:32:23.230 回答
1

您可以使用 getimagesize("img") 并检查类型。

http://php.net/manual/en/function.getimagesize.php

于 2015-04-22T13:39:21.750 回答