php缓存文件、base64图片到本地服务器

发布于 2024-01-05  894 次阅读


base64图片保存到服务器

/**
 * base64 图片保存到本地
 */
function base64ImgSaveLocal($base64code)
{
    // $base64code = 'data:image/png;base64,' . $base64code;
    $path = './aisaveimages/' . date('Y-m-d', time());
    $localFilePath = $path . '/' . time() . rand(10000, 99999) . '.png'; // 指定保存路径及文件名
    if (!is_dir($path)) {
        mkdir($path, 0777, true);
    }
    file_put_contents($localFilePath, base64_decode($base64code));
    return $localFilePath;
}

文件缓存到本地

//缓存到本地图片
function urlImageToLocal($url)
{
    if ($url == "") : return false;
    endif;
    $filename = time() . rand(10000, 99999) . '.png';
    ob_start();
    readfile($url);
    $img = ob_get_contents();
    ob_end_clean();
    $size = strlen($img);
    $path = '/aisaveimages/' . date('Y-m-d', time());
    if (!is_dir('.' . $path)) {
        mkdir('.' . $path, 0777, true);
    }
    //"../../images/books/"为存储目录,$filename为文件名
    $fp2 = fopen('.' . $path . '/' . $filename, "a+");
    fwrite($fp2, $img);
    fclose($fp2);

    return $path . '/' . $filename;
}