小编典典

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

all

我正在尝试将我的 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,这里有什么问题?


阅读 78

收藏
2022-09-02

共1个答案

小编典典

问题是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; 
}
2022-09-02