zoukankan      html  css  js  c++  java
  • php开发中将远程图片本地化的方法

    检查文本内容中的远程图片,下载远程图片到本地的方法示例。

    /**
     * 下载远程图片到本地
     *
     * @param string $txt 用户输入的文字,可能包含有图片的url
     * @param string $keywords  网站域名关键字,路径中含有这个关键字的图片(即本网站图片)跳过
     * @return string
     */
    public function getImageToLocal($txt,$keywords = 'xxx.com')
    {
    
        $matches = array();
        preg_match_all('/<img.+?src=(.+?)s/is',$txt,$matches);
        if(!is_array($matches)) return $txt;
        $curl = new curl();
        $curl -> setHeader(true);
        foreach ($matches[1] as $k => $v)
        {
            $url = trim($v,""'");
            $ext = '';
            if(strpos($url,$keywords) === false && substr($url,0,7) == 'http://') //非本站地址,需要下载图片
            {
                $curl -> setUrl($url);
                $curl -> setTimeout(5);
                $data = $curl -> send();
                list($header,$imageData) = explode("
    
    ",$data);
                if($ext = $this -> getImageExtension($header))
                {
                        $file = IMAGE_SAVE_DIR . date('YmdHis') . rand(1,100) . $k . '.' . $ext;
                        @file_put_contents($file,$imageData);
                        if(is_file($file)) $txt = str_replace($v,'"' . str_replace(ROOT,'',$file) . '"',$txt);
                }
            }
        }
        return $txt;
    }
    
    /**
     * 从HTTP头分离出图片的扩展名
     *
     * @param string $header HTTP头
     * @return string
     */
    function getImageExtension($header)
    {
        $arr = explode("
    ",$header);
        foreach($arr as $k => $v)
        {
            $line = explode(':',$v);
            if($line[0] == 'Content-Type') return str_replace('image/','',trim($line[1]));
        }
        return '';
    }
  • 相关阅读:
    第09组 Beta冲刺(4/5)
    第09组 Beta冲刺(3/5)
    第09组 Beta冲刺(2/5)
    第09组 Beta冲刺(1/5)
    第09组 Alpha事后诸葛亮
    第09组 Alpha冲刺(6/6)
    第09组 Alpha冲刺(5/6)
    第5次实践作业
    第4次实践作业
    第3次实践作业
  • 原文地址:https://www.cnblogs.com/huhangfei/p/4991823.html
Copyright © 2011-2022 走看看