To convert base64 strings generated by Nihilogic's "Canvas2Image" JavaScript tool into actual PNG files on the server using PHP, you need to perform the following steps:
Extract the base64 image data. Separate the data URI header from the actual base64 data. Here's a snippet:
$data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABE...'; list($type, $data) = explode(';', $data); list(, $data) = explode(',', $data);
Decode the base64 data. Convert the encoded data back into a binary string.
$data = base64_decode($data);
Save the image to a file. Write the decoded data to a PNG file on the server.
file_put_contents('/tmp/image.png', $data);
Alternative one-liner method: You can also use this one-line command to extract, decode, and save the image:
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
Ensure proper error handling: Implement mechanisms to detect invalid data URIs, failed base64 decoding, or incorrect image types, such as:
if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) { // Valid data URI } else { throw new \Exception('Invalid data URI'); } if ($data === false) { throw new \Exception('Base64 decode failed'); }
The above is the detailed content of How to Save PNG Images Server-Side from Base64 Data URIs using PHP?. For more information, please follow other related articles on the PHP Chinese website!