Home  >  Article  >  Backend Development  >  How to Convert Base64 String to PNG Image and Save to File?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 07:52:02339browse

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

Convert String in Base64 to Image and Save on Filesystem

Problem:
I have a string in base64 format, which represents a PNG image. Is there a way to save this image to the filesystem, as a PNG file?

Answer:

<code class="python">import base64

# Decode the base64 string into bytes
image_data = base64.decodebytes(base64_string)

# Write the decoded bytes to a file
with open("image.png", "wb") as f:
    f.write(image_data)</code>

This code will create a PNG file named "image.png" in the current working directory.

The above is the detailed content of How to Convert Base64 String to PNG Image and Save to File?. 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