Skip to content

Instantly share code, notes, and snippets.

@alexmill
Created December 8, 2015 14:45
Show Gist options
  • Save alexmill/d71b67ed84fd0150db2c to your computer and use it in GitHub Desktop.
Save alexmill/d71b67ed84fd0150db2c to your computer and use it in GitHub Desktop.
Create a base64 thumbnail from image URL (Python)
import numpy as np
import base64
import urllib
from PIL import Image
#Convert image to base64 thumbnail
def img2base64(img_link):
with open("/tmp/img_file.jpg", "wb") as f:
f.write(urllib.request.urlopen(img_link).read())
tmp_img = np.asarray(Image.open("/tmp/img_file.jpg"))
tmp_thumb = tmp_img.resize((250, 250), Image.ANTIALIAS)
tmp_thumb.save("/tmp/thumb_file.jpg")
with open("/tmp/thumb_file.jpg", "rb") as img:
thumb_string = base64.b64encode(img.read())
base64out = "data:image/jpeg;base64," + str(thumb_string)[2:-1]
return(base64out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment