将 Base64 字符串转换为图像文件? [英] Convert Base64 string to an image file?

查看:45
本文介绍了将 Base64 字符串转换为图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to convert my base64 image string to an image file. This is my Base64 string:

http://pastebin.com/ENkTrGNG

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

Using following code to convert it into an image file:

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 的错误,这是怎么回事?

But I am getting an error of invalid image, whats wrong here?

推荐答案

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

The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.

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; 
}

这篇关于将 Base64 字符串转换为图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆