Decode Base64 String to Image File in Python

This Python tutorial to learn how to convert a base64 string into an image file.

For example, we have a base64 string as below.

iVBORw0KGgoAAAANSUhEUgAAAUoAAAFKAQAAAABTUiuoAAACDklEQVR4nO2bQY6kMAxFnydItQxSHaCPEm7WVyNHqRuQ5UhBfxYEakq9obpFFaOxVyh6iy9Zdj42mNgZ+ddeEhx11FFHHXX0SNRadJC3J8p6PBwuwNFn0CRJmsCGWIFYAYIkSY/oMQIcfQYtawml20WkW4cNQKuyFwhwdEd0X49mU/74bS8S4OgPsiWoHRAE5RUCHP0GGiWNALkPgtI6oaT6GgGO7ohWW3lpfAFLt65amq4A80M7fLtWR5ds/TV+yj1rjuLjVOrtWh1l8ejNwQeRVNEIaCQs3XHx8ePbtTq6piJWNEbpflE9PHm2ToWWi+zz1mFD6SBNLH5DY6zY8AIBju6I1cHHieUtK/ehQgnViHMnCLIjBTj6/Jzwc5oNSkcbPzFbm2pMLxHg6L64TwLXi6r1P4h1OfN76yzo5gkriydsA13a5UWsbebr2ToRGkT+qGgsXauoxSeWi8/gT4OuLqNcq6Wbbe/JzVtYmq7r2du1OrrNMioCYRCqESdII9i9Mb5fq6PNE267Y2maTZoASis8Gw4X4Ogz6LY7hiiZ9bOtfmMb7Z5Fq6P33XHugXRrX2jcC+xEWv9f9OvuuHRVFFAeQqUtJ48T4OjP0NmWT2mSKmRzB38edJsTimW1n6YeUa6yNM4d6b7jertWR7/sjiFU8hCAchW5n44V4OgTqPlfC4466qijjv5D6B8v0g3DkeRA8wAAAABJRU5ErkJggg==es

The following Python code to decode the base64 string above and write to an image file named qrcode.png

import base64

base64_string = 'iVBORw0KGgoAAAANSUhEUgAAAUoAAAFKAQAAAABTUiuoAAACDklEQVR4nO2bQY6kMAxFnydItQxSHaCPEm7WVyNHqRuQ5UhBfxYEakq9obpFFaOxVyh6iy9Zdj42mNgZ+ddeEhx11FFHHXX0SNRadJC3J8p6PBwuwNFn0CRJmsCGWIFYAYIkSY/oMQIcfQYtawml20WkW4cNQKuyFwhwdEd0X49mU/74bS8S4OgPsiWoHRAE5RUCHP0GGiWNALkPgtI6oaT6GgGO7ohWW3lpfAFLt65amq4A80M7fLtWR5ds/TV+yj1rjuLjVOrtWh1l8ejNwQeRVNEIaCQs3XHx8ePbtTq6piJWNEbpflE9PHm2ToWWi+zz1mFD6SBNLH5DY6zY8AIBju6I1cHHieUtK/ehQgnViHMnCLIjBTj6/Jzwc5oNSkcbPzFbm2pMLxHg6L64TwLXi6r1P4h1OfN76yzo5gkriydsA13a5UWsbebr2ToRGkT+qGgsXauoxSeWi8/gT4OuLqNcq6Wbbe/JzVtYmq7r2du1OrrNMioCYRCqESdII9i9Mb5fq6PNE267Y2maTZoASis8Gw4X4Ogz6LY7hiiZ9bOtfmMb7Z5Fq6P33XHugXRrX2jcC+xEWv9f9OvuuHRVFFAeQqUtJ48T4OjP0NmWT2mSKmRzB38edJsTimW1n6YeUa6yNM4d6b7jertWR7/sjiFU8hCAchW5n44V4OgTqPlfC4466qijjv5D6B8v0g3DkeRA8wAAAABJRU5ErkJggg==es'

image_data = base64.b64decode(base64_string)
f = open('qrcode.png', 'wb')
f.write(image_data)
f.close()

Execute the Python code we have the qrcode.png file be written as below screenshot.

Sample Image

Happy Coding 😊