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

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

Susan Sarandon
Release: 2024-12-09 16:43:17
Original
527 people have browsed it

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

Saving PNG Images Server-Side from Base64 Data URIs

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:

  1. 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);
    Copy after login
  2. Decode the base64 data. Convert the encoded data back into a binary string.

    $data = base64_decode($data);
    Copy after login
  3. Save the image to a file. Write the decoded data to a PNG file on the server.

    file_put_contents('/tmp/image.png', $data);
    Copy after login
  4. 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));
    Copy after login
  5. 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');
    }
    Copy after login

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!

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