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

How to Save PNG Images from Base64 Data URIs using PHP?

Linda Hamilton
Release: 2024-11-28 11:07:11
Original
950 people have browsed it

How to Save PNG Images from Base64 Data URIs using PHP?

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

  1. Extract the image data: The base64 data is usually formatted as "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABE...". Extract the data portion after the comma.
  2. Decode the data: Use the base64_decode function to convert the base64 string back into its binary representation.

Saving the PNG Image

  1. Use file_put_contents: To store the decoded data as a PNG image on the server, use the file_put_contents function. Specify the file path and the decoded data as arguments.

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

One-Liner Version:

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

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!

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