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

Barbara Streisand
Release: 2024-10-20 07:52:29
Original
135 people have browsed it

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>
Copy after login
  1. Open a file for writing in binary mode:
<code class="python">with open("image.png", "wb") as f:</code>
Copy after login
  1. Write the raw image data to the file:
<code class="python">    f.write(img_data)</code>
Copy after login
  1. Close the file:
<code class="python">f.close()</code>
Copy after login

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!