Example encode and decode image using base64 in Python


This is the simple way to encode images using base64 library in Python and decoded it back into the images based on the string encoded results. Here is the code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import base64

def convert(image):
    f = open(image)
    data = f.read()
    f.close()

    string = base64.b64encode(data)
    convert = base64.b64decode(string)

    t = open("example.png", "w+")
    t.write(convert)
    t.close()

if __name__ == "__main__":
    convert("test.png")

In this example, I put “test.png” images into the same level of this scripts. Happy encoding & decoding! 😀


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.