【问题标题】:function for saving images issue保存图像的功能问题
【发布时间】:2015-06-30 04:36:52
【问题描述】:

我创建了一个带有两个输入参数的函数。 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;
}
}

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

希望我已经足够清楚了。

【问题讨论】:

    标签: php curl save-image


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我使用了你的功能以便能够对其进行测试,它完成了我的工作。
    【解决方案2】:

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

    }

    【讨论】:

      猜你喜欢
      • 2012-10-28
      • 2010-12-29
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多