Sometimes, we want to convert string in base64 to image and save on file system with Python.
In this article, we’ll look at how to convert string in base64 to image and save on file system with Python.
How to convert string in base64 to image and save on file system with Python?
To convert string in base64 to image and save on file system with Python, we can use the base64.decodebytes
method.
For instance, we write:
img_data = b'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
import base64
with open("img.png", "wb") as fh:
fh.write(base64.decodebytes(img_data))
We have a byte string with the base64 image data assigned to img_data
.
Then we open the img.png file with open
.
We open it with write permission by passing in 'wb'
.
Then we call fh.write
with base64.decodebytes(img_data))
to write the decoded base64 byte string as the content of the img.png to save the image.
As a result, img.png should have a red cross as its content.
Conclusion
To convert string in base64 to image and save on file system with Python, we can use the base64.decodebytes
method.