Python2/Python3 Base64 Encoded Image

vegaseat 5 Tallied Votes 8K Views Share

If you have a smaller image, you can include it in your program as a base64 encoded string. This way you don't have to worry about an image file to go with your code. In your program you can then decode it back to the familiar bytes of an image and use it. This code snippet should work with Python2 and Python3 versions.

'''Base64encJPEG.py

create a base64 image string
changes the bytes of an image file into printable char combinations
that you can include in your program

tested with Python 2.7.3 and Python 3.3.0  by  vegaseat  11nov2012
'''

import base64

# pick an image file you have in the working directory
# or give full path
img_file = "Btn_rainbow.jpg"
b64 = base64.encodestring(open(img_file,"rb").read())
try:
    # Python2
    print("rainbow_jpg_b64='''\\\n" + b64 + "'''")
except TypeError:
    # Python3
    print("rainbow_jpg_b64='''\\\n" + b64.decode("utf8") + "'''")

"""copy and paste from here ...

rainbow_jpg_b64='''\
/9j/4AAQSkZJRgABAQEAyADIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAoACgDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHB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Q898Q8z4VzDPK
WXUK+V5DLKcOssoV8NTnhqOLlWpyrRr4rFOVZOrKLnCVOLhGPucycn//2Q==
'''

"""
Gribouillis 1,391 Programming Explorer Team Colleague

Here is how to display the base64 image using tkinter and PIL in python 2

if __name__ == "__main__":
    from StringIO import StringIO
    import Tkinter
    from PIL import ImageTk, Image

    root = Tkinter.Tk()
    #root.bind("<Button>", lambda event: event.widget.quit())
    root.geometry('+%d+%d' % (100,100))
    f = StringIO(base64.decodestring(str(rainbow_jpg_b64)))
    image = Image.open(f)
    zoom = 5
    image = image.resize((zoom*image.size[0], zoom*image.size[1]))
    root.geometry('%dx%d' % (image.size[0], image.size[1]))
    tkpi = ImageTk.PhotoImage(image)
    label_image = Tkinter.Label(root, image=tkpi)
    label_image.place(x=0,y=0,width=image.size[0],height=image.size[1])
    root.title("rainbow")
    root.mainloop()

Nice rainbow!

Lardmeister 461 Posting Virtuoso

Thanks Gribouillis, to make your code example work with Python3 I modified it a little:

'''tk_base64_jpg_image1.py
use a base64 encoded non-gif image with Tkinter and PIL
tested with Python27 and Python33
'''

import base64
import io
from PIL import ImageTk, Image
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3+
    import tkinter as tk

# the base 64 encoded image
rainbow_jpg_b64='''\
/9j/4AAQSkZJRgABAQEAyADIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAoACgDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk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V4zcUvP+No5piMxdWU3PB4rD0KfNOcKj9yv
g8U7c0U7c3kfxb4A+Cfhv4QeIlHjLgzh6hh87p1q9aNTGP29HnqzhKV6dGOGm1eKt+8uu5+Tn/BQ
X9s34NftBfD/AMVWvhfxroF7rU2k3629rb6naSNfN5MvyQoj/vJ/+eMf/Lf3uP8AWlFFfp/gnwLk
nh7wrU4fyCeO/s6ni/bU442vSrVISlThBwjOjQw8fZpU4uMXBuLbs0uVR/tLx98Q898Q8z4VzDPK
WXUK+V5DLKcOssoV8NTnhqOLlWpyrRr4rFOVZOrKLnCVOLhGPucycn//2Q==
'''

root = tk.Tk()

try:
    # Python2
    jpg_str = base64.b64decode(rainbow_jpg_b64)
    f = io.BytesIO(jpg_str)
except TypeError:
    # Python3
    jpg_bytes = base64.b64decode(rainbow_jpg_b64.encode())
    f = io.BytesIO(jpg_bytes)

# get the non-gif image with PIL
pil_img = Image.open(f)
width = pil_img.size[0]
height = pil_img.size[1]
# optionally enlarge the image
zoom = 6
pil_img = pil_img.resize((zoom*width, zoom*height))
# get new width and height of the enlarged image
width2 = pil_img.size[0]
height2 = pil_img.size[1]
# set the root window to the enlarged image size
root.geometry('%dx%d' % (width2, height2))

# convert to an image Tkinter can handle
tk_image = ImageTk.PhotoImage(pil_img)
label = tk.Label(root, image=tk_image)
#label.place(x=0, y=0, width=width2, height=height2)
label.pack()

# optionally bind label to left mouse click ...
label.bind("<Button>", lambda event: event.widget.quit())

root.title("rainbow %dx%d" % (width2, height2))

root.mainloop()
Gribouillis commented: great +13
ZZucker 342 Practically a Master Poster

Thanks Lardmeister for pointing out that the introduction of byte strings in Python3 makes quite a few changes to Python2 code. I guess it eliminates some of the unicode problems.

HiHe 174 Junior Poster

With the Tkinter GUI toolkit it is much simpler to use GIF files:

'''Base64encodedGIF.py
create a base64 encoded image string from a .gif image file
changes the bytes of an image file into printable char combinations

You can then copy and paste the result into your program.
With Tkinter you can use the b64 data directly
photo = tk.PhotoImage(data=grape_gif_b64)

For some other GUI toolkits you can decode with    
ladybug_gif = base64.b64decode(grape_gif_b64)
to get a string that resembles the actual gif file

works with Python2 and Python3
'''

import base64
import os

# pick an image file you have in the working directory
# or give the full path
img_file = "grape.gif"

# create the b64 variable name
name, ext = os.path.splitext(img_file.lower())
vname = "%s_%s_b64" % (name, ext[1:])

b64 = base64.encodestring(open(img_file,"rb").read())
try:
    # Python2
    print(vname + "='''\\\n" + b64 + "'''")
except TypeError:
    # Python3
    print(vname + "='''\\\n" + b64.decode("utf8") + "'''")

"""result, copy and paste from here ...

grape_gif_b64='''\
R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9PT6Ai8P8A////
/////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYYfh8GIEvpoUZcmtOKAO5rLMva
0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYwYtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eT
YhJDQ3woDGl7foNiKBV7aYeEkHEignKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOs
NYa2q7mcirC5I5FofsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
'''

"""
HiHe 174 Junior Poster

Here is the Tkinter example:

''' Tk_Canvas_Image_b64.py
a base64 encoded GIF image string is simple to use with Tkinter
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

# base64 encoded GIF image string
grape_gif_b64='''\
R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9PT6Ai8P8A////
/////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYYfh8GIEvpoUZcmtOKAO5rLMva
0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYwYtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eT
YhJDQ3woDGl7foNiKBV7aYeEkHEignKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOs
NYa2q7mcirC5I5FofsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
'''

root = tk.Tk()
root.title("display a base64 encoded gif image")

photo = tk.PhotoImage(data=grape_gif_b64)

# create a white canvas
cv = tk.Canvas(bg='white')
cv.pack(side='top', fill='both', expand='yes')

# put the image on the canvas with
# create_image(xpos, ypos, image, anchor)
cv.create_image(150, 50, image=photo, anchor='nw')

root.mainloop()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.