php图片本地化

//内容图片本地化
function getCurContent($content)
{
    //匹配图片地址
    $reg = '/<img (.*?)+src=[\'"](.*?)[\'"]/i';
    preg_match_all( $reg , $content , $img_array );
    $bb = $img_array[2];
    //移除重复的Url
    $img_array = array_unique($bb);
    if ($img_array != '') {
        $imgUrl = DS . 'uploads' . DS . date("Ymd") . DS;
        $imgPath = ROOT_PATH . $imgUrl;
        $htd = new Http();
        foreach ($bb as $key => $value) {
            //获取hash
            $md5 = strtolower($htd->getHash($value, true));
            $filemode = Db::name('file');
            $n = $filemode->where('md5', $md5)->find();
            $realpath = '';
            if (empty($n)) {
                $itype = substr(strrchr($value, '.'), 1);
                $milliSecondN = md5(microtime(true));
                $rndFileName = $imgPath . $milliSecondN . '.' . $itype;
                $fileurl = $imgUrl . $milliSecondN . '.' . $itype;
                $rs = $htd->http_down($value, $rndFileName);
                //抓取成功
                if ($rs) {
                    $path = str_replace("\\", "/", $fileurl);
                    $realpath = WEB_URL . $path;
                    //写入数据库
                    $data['sha1'] = sha1($rndFileName);
                    $data['md5'] = md5($rndFileName);
                    $data['create_time'] = time();
                    $data['size'] = filesize($rndFileName);
                    $data['name'] = $milliSecondN . '.' . $itype;
                    $data['ext'] = $itype;
                    $data['savepath'] = $realpath;
                    $data['savename'] = $milliSecondN . '.' . $itype;
                    Db::name('file')->insert($data);
                }
            } else {
                $realpath = $n['savepath'];
            }
            $content = str_replace($value, $realpath, $content);
        }
    }
    return $content;
}


分类: PHP 点赞(0) 收藏

评论