Home  >  Article  >  Backend Development  >  How to Decode a Base64-Encoded Image and Save it to Disk?

How to Decode a Base64-Encoded Image and Save it to Disk?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 07:48:29295browse

How to Decode a Base64-Encoded Image and Save it to Disk?

Converting a base64-encoded string to an image and saving it to the file system

Problem

I have a string in base64 format representing a PNG image. How do I save this image to the file system as a PNG file?

Answer

<code class="python">import base64

# Decode the base64-encoded string and convert it into binary data.
binary_data = base64.b64decode(string_data)

# Save the binary data to a file.
with open('image.png', 'wb') as f:
    f.write(binary_data)</code>

In this example, string_data is a base64-encoded string, and image.png is the desired filename for the saved image.

The above is the detailed content of How to Decode a Base64-Encoded Image and Save it to Disk?. 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