PHP Base64 Image Decoding: Fixing File Corruption Issues

php base64 decodesave base64 imagedata:image/pngfile_put_contentsbase64 encoding
Published·Modified·

PHP provides excellent support for Base64 with built-in functions base64_encode and base64_decode for encoding and decoding images.

For encoding, simply read the image stream and use base64_encode to generate the encoded string.

Decoding is slightly more complex. When an image is encoded into a Base64 string, it often includes a prefix like data:image/png;base64, which is intended for Base64 identification. However, directly passing this string to the base64_decode function in PHP will result in a corrupted image file. The solution is to remove this prefix string first.

$base64_string = explode(',', $base64_string); // Extract characters after the comma in 'data:image/png;base64'
$data = base64_decode($base64_string[1]);      // Decode the extracted characters using base64_decode
file_put_contents($url, $data);                // Write to file and save

Original source: PHP Base64 Image Decoding Issues - winyh. All rights reserved by the original author. If there is any infringement, please contact QQ: 337003006 for removal.