Wednesday, June 28, 2017

How To: Create Thumbnail Image From Base64 Encoded String using Python 3

In this tutorial we 'll create thumbnail image from base64 encoded string received from client/user using python 3.
Our purpose is to create a thumbnail image for each image saved by client/user so that we can send back thumbnail images instead large size images while sending bulk data over the internet.

We are receiving image in form of base64 encoded string, We 'll apply following steps on it for complete result.

1). Decode string using base64 technique.
2). Create temporary image from decoded string.
3). Create thumbnail from this temporary image.
4). Encode thumbnail using base64 technique, so that we can save thumbnail as well in our database.
5). Remove both newly created temporary image and its thumbnail after saving to database.

1). Decode string using base64 technique.

# UserImage holds base64 encoded string. 
TmpUserImage = UserImage.replace("data:image/jpeg;base64,", "") 
ImgDataDecoded = base64.b64decode(TmpUserImage)

2). Create temporary image from decoded string.

# Using uuid for unique file name.
TmpUUID = str(uuid.uuid4()) 
# File name
FileName = TmpUUID + '_image.jpeg' 
# Thumbnail name
FileNameThumb = TmpUUID + '_image_80x80.jpeg' 
# Writing to file.
with open(FileName, 'wb') as f: 
   f.write(ImgDataDecoded)

3). Create thumbnail from this temporary image.

image = Image.open(FileName) 
size = (80, 80) 
thumb = ImageOps.fit(image, size, Image.ANTIALIAS) 
thumb.save(FileNameThumb)

4). Encode thumbnail using base64 technique, so that we can save thumbnail as well in our database.

with open(FileNameThumb, "rb") as thmbn: 
    TmpStr = base64.b64encode(thmbn.read()) 
TmpStr = "data:image/jpeg;base64," + str(TmpStr)[2:-1] 
# Encode to utf-8 before saving to database 
# (don't forget to decode after fetching from database).
TmpStr = bytes(TmpStr,"utf-8")
# Now save TmpStr to database.

5). Remove both newly created temporary image and its thumbnail after saving to database.

if os.path.isfile(FileName): 
    os.remove(FileName) 
if os.path.isfile(FileNameThumb): 
    os.remove(FileNameThumb)

Don't forget to include following libraries.

# For Thumbnail 
from PIL import Image, ImageOps 
import base64, uuid, os

This is all, you have done it. Please ask in comment if there is any confusion. Happy Coding -:)

No comments:

Post a Comment