php 远程图片本地化

/**
 * 把新浪的远程图片下载到自己服务器上
 *
 * @access  public
 * @param   goods_desc      $goods_desc         要处理的内容
 * @return  mix         如果成功返回缩略图的路径,失败则返回false
 */
function GetCurSinImg($goods_desc)
{
    $body = stripslashes($goods_desc);
    $img_array = array();
    //获取从新浪复制过来的src的地址
    preg_match_all('/<img.*?src="(.*?)".*?>/is',$body,$img_array);
    $img_array = array_unique($img_array[1]);

    set_time_limit(0);
    $imgurl = "bdimages/upload1/".date('Ymd');
    $imgpath = ROOT_PATH.$imgurl;

    $millisecond = date("YmdHms");
    if (!file_exists($imgpath))
    {
        if (!make_dir($imgpath))
        {
            return false;
        }
    }
    else
    {

        foreach($img_array as $key =>$value)
        {
            $value = trim($value);
            //根据图片的路径获取图片的后缀
            $imgAttr = get_headers($value,true);
            switch($imgAttr['Content-Type']){
                case 'image/png' :
                    $ext = 'png';
                    break;
                case 'image/jpeg' :
                    $ext = 'jpg';
                    break;
                case 'image/gif' :
                    $ext = 'gif';
                    break;
                default:
                    $ext = 'jpg';
            }
            
            
            
            $get_file = @file_get_contents($value);
            $rndfilename = $imgpath."/".$millisecond.$key.".".$ext;
            $fileurl = "/".$imgurl."/".$millisecond.$key.".".$ext;
            
            if($get_file)
            {
                $fp = @fopen($rndfilename,"w");
                @fwrite($fp,$get_file);
                @fclose($fp);
            }
            //echo $rndfilename."<br/>".$fileurl."<br/>";
            $body = str_replace($value,$fileurl,$body);
        }
    }
    $body = addslashes($body);
    return $body;
}

 

posted @ 2016-11-03 11:36  Abner3721  阅读(1525)  评论(0编辑  收藏  举报