Home  >  Article  >  Backend Development  >  How to Convert and Save a Base64-Encoded Image to the Filesystem in Python?

How to Convert and Save a Base64-Encoded Image to the Filesystem in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 07:52:29138browse

How to Convert and Save a Base64-Encoded Image to the Filesystem in Python?

Convert string in base64 to image and save on filesystem

Given a string in base64 format, which represents a PNG image, a common task is to need to save this image to the filesystem, as a PNG file.

Here are steps to convert a base64 string to an image and save it to the filesystem using Python:

  1. Decode the base64 string to get the raw image data:
<code class="python">import base64

img_data = base64.b64decode(base64_string)</code>
  1. Open a file for writing in binary mode:
<code class="python">with open("image.png", "wb") as f:</code>
  1. Write the raw image data to the file:
<code class="python">    f.write(img_data)</code>
  1. Close the file:
<code class="python">f.close()</code>

Here is a complete example:

<code class="python">import base64

# Replace "base64_string" with the actual base64-encoded string
base64_string = ""

img_data = base64.b64decode(base64_string)

with open("image.png", "wb") as f:
    f.write(img_data)</code>

This will save the PNG image to a file named "image.png" in the current directory.

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

Statement:
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