Convert Image File to Base64 String in Python

This python tutorial to show how to convert an image file or any file into a string of base64 format.

For example we have an image named qrcode.png as below.

QR Code Image to Bae64

Following Python code to convert image into base64 string.

import base64

f = open('qrcode.png', 'rb')
image_base64 = base64.b64encode(f.read())
image_base64_string = image_base64.decode('utf-8')

print(image_base64_string)

The output as below.

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

Happy Coding 😊