Home > Backend Development > PHP Tutorial > Problem with php saving Base64 image base64_decode

Problem with php saving Base64 image base64_decode

黄舟
Release: 2023-03-16 12:04:01
Original
1859 people have browsed it

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); //写入文件并保存
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template