Home > Backend Development > Python Tutorial > How to Convert Base64 Encoded String to Image and Save to File?

How to Convert Base64 Encoded String to Image and Save to File?

Susan Sarandon
Release: 2024-10-20 07:57:29
Original
692 people have browsed it

How to Convert Base64 Encoded String to Image and Save to File?

Convert string in base64 to image and save on filesystem

Base64 encoding is a binary-to-text encoding scheme that represents binary data in an ASCII string format. It is commonly used to encode non-textual data such as images, audio, and binary files.

To convert a base64-encoded string to an image and save it to the filesystem, you can use the following steps:

  1. Decode the base64-encoded string to obtain the original binary data.
  2. Create a new file with the appropriate extension (e.g., .png, .jpg, .gif) using open().
  3. Write the decoded binary data to the file using write().
  4. Close the file.

Here is an example of how to perform these steps in Python:

import base64

# Decode the base64-encoded string
decoded_data = base64.b64decode(base64_string)

# Create a new file
with open('image.png', 'wb') as f:
    # Write the decoded binary data to the file
    f.write(decoded_data)
Copy after login

In this example, base64_string is the base64-encoded string, and image.png is the name of the file to be created.

Once the file is saved, you can verify that the image has been correctly decoded by opening it in an image viewer.

The above is the detailed content of How to Convert Base64 Encoded String to Image and Save to File?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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