将base64保存到本地

首页 > PHP > Thinkphp6 更新日期:2024-11-13 10:01:32

解码base64数据

# 解码base64
function jiexiBase($base64Image) {
    $pos = strpos($base64Image, ',');
    if ($pos!== false) {
        return substr($base64Image, $pos + 1);
    } else {
        // 如果没有找到',',可能数据格式有问题,返回空字符串或者抛出异常
        return '';
    }
}

将解码后的base64数据,保存到本地

/*
 * 将base64图片保存到本地
 * $basePath => "base64图片"
 * $filename => "保存的路径,绝对路径"  如:'D:/abc/bbb'
 * $type => "要保存的图片类型,默认为jpg"
 * */
function saveBase($basePath, $filename, $type = "jpg"){

    $base64Data = jiexiBase($basePath);
    $imageData = base64_decode($base64Data);

    $filename = $filename. uniqid().".".$type;

    if (file_put_contents($filename, $imageData)) {
        return "图像保存成功";
    } else {
        return "图像保存失败";
    }

}

使用

$res = saveBase($base, 'D:/file/');
dd($res);


标题导航