Home > Web Front-end > JS Tutorial > How to Save PNG Files from Base64 Data URIs Using PHP?

How to Save PNG Files from Base64 Data URIs Using PHP?

Patricia Arquette
Release: 2024-12-06 12:12:18
Original
1024 people have browsed it

How to Save PNG Files from Base64 Data URIs Using PHP?

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);
Copy after login

To simplify the process, use a one-liner:

$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
Copy after login

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
}
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template