base64image,图片互转


 

function base64_to_image($base64img, $path = '', $imageName = null)
{
    // 匹配出图片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64img, $result)) {
        $type = $result[2];
        // 指定文件存放的目录
        $newFile = $path.'/';
        // 检查是否有该文件夹,如果没有就创建,并给予最高权限
        if (!is_dir($newFile)) {
            mkdir($newFile, 755);
        }
        // 组合图片地址(图片存放地址+图片名+图片后缀)
        $newFile = null == $imageName ? $newFile.time().".{$type}" : $newFile.$imageName.".{$type}";
        // 保存图片
        if (file_put_contents($newFile, base64_decode(str_replace($result[1], '', $base64img)))) {
            // 返回图片地址路径
            return $newFile;
        }
    }

    return false;
}

 

 

 

/**
 * 本地文件转为base64.
 *
 * @param string $file 文件路径
 *
 * @return string
 */
function image_to_base64($file)
{
    if ($fp = fopen($file, 'r', 0)) {
        $gambar = fread($fp, filesize($file));
        fclose($fp);

        // 'data:image/jpg/png/gif;base64,'.$buffer
        return 'data:image/png;base64,'.chunk_split(base64_encode($gambar));
    }

    return '';
}

 

发布时间 : 2023-03-01,阅读量:977
本文链接:https://upwqy.com/details/23.html
远程文件下载 ThinkPHP URL重写