PHP將圖片轉base64編碼以及base64圖片轉換爲圖片並保存代碼

一: 圖片轉base64編碼

/*圖片轉換爲 base64格式編碼*/
$img = 'uploads/01.png';
$base64_img = base64EncodeImage($img);
echo '<img src="' . $base64_img . '" />';

function base64EncodeImage ($image_file) {
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}

二:base64圖片轉換爲圖片並保存

/*  base64格式編碼轉換爲圖片並保存對應文件夾 */
function base64_image_content($base64_image_content,$path){
    //匹配出圖片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        $type = $result[2];
        $new_file = $path."/".date('Ymd',time())."/";
        if(!file_exists($new_file)){
            //檢查是否有該文件夾,若是沒有就建立,並給予最高權限
            mkdir($new_file, 0700);
        }
        $new_file = $new_file.time().".{$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;
    }
}

echo base64_image_content($base64_img,"uploads/");

 

來源於:小灰灰博客php

https://xiaohuihui.net.cn/archives/940.htmlhtml

 

更多技術知識請訪問小灰灰博客:ui

https://xiaohuihui.net.cn/編碼

相關文章
相關標籤/搜索