Home > Article > Backend Development > Problem with php saving Base64 image base64_decode
PHP has very good support for Base64, with built-in base64_encode and base64_decode responsible for Base64 encoding and decoding of images.
In terms of encoding, just read the image stream and then use base64_encode to encode it.
The decoding is a little more troublesome. The reason is that after encoding the image into a base64 string, these characters data:image/png;base64 will be added to the encoding, which is originally used for base64 recognition. However, if you put it directly into PHP and use the base64_decode function to decode it, the final saved image file format will be damaged. The solution is to remove this string of characters first:
$base64_string= explode(',', $base64_string); //截取data:image/png;base64, 这个逗号后的字符 $data= base64_decode($base64_string[1]); //对截取后的字符使用base64_decode进行解码 file_put_contents($url, $data); //写入文件并保存
The above is the detailed content of Problem with php saving Base64 image base64_decode. For more information, please follow other related articles on the PHP Chinese website!