How to convert image to base64 using Python

Free Python Code - Aug 26 '23 - - Dev Community

Hi 🙂🖐

In this post i will share with you how to convert image to base64 using Python

step 1

You need image for test

step 2

Read the image using rb as the reading mode to read bytes from the image and encode them.

import base64

with open('alone.jpg', 'rb') as img:
    base64_bytes = base64.b64encode(img.read())
Enter fullscreen mode Exit fullscreen mode

Now we have base64_bytes
we need to decode this using decode function

base64_str = base64_bytes.decode()

f = open('base64_str.txt', 'a+')
f.write(base64_str)
f.close()
Enter fullscreen mode Exit fullscreen mode

Now that we have a base64 string in the text file base64_str.txt, we can use this to display an image from the base64 string by copying all of base64_str.txt and using sites like codebeautify.

https://codebeautify.org/base64-to-image-converter

Result

Image description

Now we're done 🤗

Don't forget to like and follow 🙂

Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .