How to download file and make thumb in Python

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


pip install requests Pillow


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):
        im =
        tm =, THUMB_SIZE), '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 =
    path = "/tmp/{fname}.{ext}".format(fname=fname, ext=ext)

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