Skip to content

Instantly share code, notes, and snippets.

@mjdietzx
Last active March 21, 2024 11:12
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save mjdietzx/545fa2874b2688e9bcb71e2ee92cd5a0 to your computer and use it in GitHub Desktop.
Save mjdietzx/545fa2874b2688e9bcb71e2ee92cd5a0 to your computer and use it in GitHub Desktop.
Download image from url and save as file
import io
from PIL import Image # https://pillow.readthedocs.io/en/4.3.x/
import requests # http://docs.python-requests.org/en/master/
# example image url: https://m.media-amazon.com/images/S/aplus-media/vc/6a9569ab-cb8e-46d9-8aea-a7022e58c74a.jpg
def download_image(url, image_file_path):
r = requests.get(url, timeout=4.0)
if r.status_code != requests.codes.ok:
assert False, 'Status code error: {}.'.format(r.status_code)
with Image.open(io.BytesIO(r.content)) as im:
im.save(image_file_path)
print('Image downloaded from url: {} and saved to: {}.'.format(url, image_file_path))
@Himura2la
Copy link

Himura2la commented Oct 5, 2018

Just perfect, thanks! It was strange to find that such a common task is not solved on first link in google.
A one-liner version: PIL.Image.open(io.BytesIO(request.urlopen(url).read())).save(image_file_path)

@f22hd
Copy link

f22hd commented Jul 24, 2020

Thank you so much for sharing the code. It helps me a lot.

@tegeuz
Copy link

tegeuz commented Mar 18, 2021

Perfect! The only one that works 100%
Thank you

@Bharat1056
Copy link

how to use it can anyone explain?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment