gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:45:51 24 4
gpt4 key购买 nike

我正在尝试将我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com