Saving PNG Files from Base64 Data URIs Server-Side with PHP
When converting canvas drawings to PNG images using tools like Nihilogic's "Canvas2Image," there often arises a need to store these images on a server using PHP. This can be achieved by decoding the base64 strings generated by the tool and creating actual PNG files.
To do this, extract the base64 data by splitting the data URI string on the semicolon (';') and comma (','). Decode the data using the base64_decode function and pass it to the file_put_contents function to save the file to the desired location.
For example:
$data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABE...'; list($type, $data) = explode(';', $data); list(, $data) = explode(',', $data); $data = base64_decode($data); file_put_contents('/tmp/image.png', $data);
To simplify the process, use a one-liner:
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
For error handling and validation of the image type, you can use the following:
if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) { // ... validation and processing }
By following these steps, you can effectively save PNG images from base64 data URIs on your server using server-side PHP code.
The above is the detailed content of How to Save PNG Files from Base64 Data URIs Using PHP?. For more information, please follow other related articles on the PHP Chinese website!