php - 将 Base64 字符串转换为图像文件?

标签 php base64

我正在尝试将我的 base64 图像字符串转换为图像文件。这是我的 Base64 字符串:

http://pastebin.com/ENkTrGNG

使用以下代码将其转换为图像文件:

function base64_to_jpeg( $base64_string, $output_file ) {
    $ifp = fopen( $output_file, "wb" ); 
    fwrite( $ifp, base64_decode( $base64_string) ); 
    fclose( $ifp ); 
    return( $output_file ); 
}

$image = base64_to_jpeg( $my_base64_string, 'tmp.jpg' );

但是我收到invalid image的错误,这里有什么问题?

最佳答案

问题是 data:image/png;base64, 包含在编码内容中。这将导致 base64 函数解码时图像数据无效。在解码字符串之前删除函数中的数据,就像这样。

function base64_to_jpeg($base64_string, $output_file) {
    // open the output file for writing
    $ifp = fopen( $output_file, 'wb' ); 

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );

    // we could add validation here with ensuring count( $data ) > 1
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );

    // clean up the file resource
    fclose( $ifp ); 

    return $output_file; 
}

关于php - 将 Base64 字符串转换为图像文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15153776/

相关文章:

javascript - tinymce图片上传php插件什么的

php - 无法使用 file_get_contents 找到包装器 "https"

oauth - 使用base64编码生成Oauth授权 token

c# - Base64编码的字符串可以以3个等号结尾吗?

javascript - 如何将 base64 保存到 cordova/ionic 上的图像文件或上传到服务器?

php - Mysql - 如何获取连续预订一定天数的用户?

javascript - 选中后获取所有表行值

php - a href tel 和标准浏览器

java - Base64 解码并解压缩字符串

mysql - Bash:Base64 编码非常大的 .csv 中的 1 列并输出到新文件