base64圖片保存到本地

//路徑以/市id/縣公司id/專賣證號/照片名稱格式
$image = file_get_contents('./cityid/1.txt');     //圖片base64碼
$path = "./cityid/area_company_id/411302125124/"; //文件保存地址
$file_name = 'photo';         //文件名稱,不包含後綴
$url = base64_image_content($image,$path,$file_name);
echo $url;
 
/*  base64格式編碼轉換爲圖片並保存對應文件夾 */
function base64_image_content($base64_image_content,$path,$file_name){
    //匹配出圖片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        $type = $result[2];
        $new_file = $path;
        if(!file_exists($new_file)){
            //檢查是否有該文件夾,如果沒有就創建,並給予最高權限
            mkdir($new_file, 0777,true);
        }
        $new_file = $new_file.$file_name.".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            return '/'.$new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章