我正在尝试将我的 base64 图像字符串转换为图像文件。这是我的 Base64 字符串:
使用以下代码将其转换为图像文件:
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/