How to download file and make thumb in Python Python 27.05.2016

Simple snippet how to download file with requests and make preview in Python.

Preparation

pip install requests Pillow

Snippet

import os
import requests
from PIL import Image, ImageOps
from StringIO import StringIO

THUMB_SIZE = (315, 320)
HEADERS = {'User-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36'}

#
# helper function
#

def make_thumb(image_path, thumb_path):
    try:
        im = Image.open(image_path)
        tm = ImageOps.fit(im, THUMB_SIZE)
        tm.save(thumb_path, 'JPEG', quality=75)
        return os.stat(thumb_path).st_size
    except IOError as e:
        print e.errno, e.strerror

#
# get image from url
#

fname = "img1"
r = requests.get(url, headers=HEADERS)
img, ext = r.headers['content-type'].split('/')

#
# save image
#

path = ""
if img == "image":
    i = Image.open(StringIO(r.content))
    path = "/tmp/{fname}.{ext}".format(fname=fname, ext=ext)
    i.save(path)

    # make thumb
    path_thumb = "/tmp/{fname}_thumb.jpeg"
    make_thumb(path, path_thumb)
else:
    print("There is no image.")