Saving PNG Images from Base64 Data URIs on the Server-Side with PHP
When working with JavaScript canvas drawings, you may encounter the need to save the generated PNG images on the server for storage or further processing. One common approach to achieve this is through a base64 data URI, which converts the image into a text string. This article will guide you through the steps to effectively decode this base64 string and save it as a PNG image using PHP.
Decoding the Base64 Data
Saving the PNG Image
Example:
$data = 'data:image/png;base64,AAAFBfj42Pj4'; list($type, $data) = explode(';', $data); list(, $data) = explode(',', $data); $data = base64_decode($data); file_put_contents('/tmp/image.png', $data);
One-Liner Version:
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
Error Checking:
Include error checking to ensure the data is valid and the decoding process is successful. Use preg_match to verify the data format and base64_decode to check for decoding errors.
The above is the detailed content of How to Save PNG Images from Base64 Data URIs using PHP?. For more information, please follow other related articles on the PHP Chinese website!