Explain Codes LogoExplain Codes Logo

How do I read image data from a URL in Python?

python
image-processing
requests-library
pil-library
Nikita BarsukovbyNikita Barsukov·Dec 12, 2024
TLDR

To fetch image data from a URL in Python, you need to use the requests library to request the content and the Pillow library to open it:

from PIL import Image import requests from io import BytesIO img_data = requests.get('YOUR_IMAGE_URL').content image = Image.open(BytesIO(img_data))

Make sure to replace YOUR_IMAGE_URL with your image's URL. This code-snippet provides a Pillow Image object from the image fetched from the given URL.

Tips for heavy files: streaming

When dealing with large images, your memory could blow up like a balloon 🎈. Utilize streaming to avoid this:

response = requests.get('YOUR_IMAGE_URL', stream=True) # Drunken master: staggers to avoid blackout. response.raw.decode_content = True image = Image.open(response.raw)

Enabling stream=True sets requests to download in chunks, instead of one big haul. Do remember to use response.raw.decode_content = True to correctly decode the content stream!

Uncommon image formats: the rare beast taming guide

Think you are dealing with a rarely-seen image format? No worries, tame it by converting:

import requests from io import BytesIO from PIL import Image response = requests.get('YOUR_IMAGE_URL') image = Image.open(BytesIO(response.content)) if image.format == 'SOME_RARE_FORMAT': # You rarely seen unicorn? Tame it! image = image.convert('RGB') # Convert to common format, if needed

The image.format attribute tells the tale of its origin. You can convert the rare beast to a commoner with image.convert() .

Syntax of invincibility: error handling

Error handling: the most important spell in Programmers vs Bugs universe. Let's see how to make it to the final round!

import requests from PIL import Image from io import BytesIO try: response = requests.get('YOUR_IMAGE_URL') response.raise_for_status() image = Image.open(BytesIO(response.content)) except requests.HTTPError as http_err: print(f'HTTP error occurred: {http_err}') # Uh-oh, the 4 horsemen arrive! except Exception as err: print(f'Other error occurred: {err}') # If it's not horsemen, it's zombies. 💀

The response.raise_for_status() lifts the veil on HTTP errors- revealing the 4 horsemen! The Exception catchall is the last line of defense against unknown forces! Who's next - zombies?!

Faster than light: optimizing speed and memory

You want to be flash and save the day without burning out memory. Here's the superpower kit:

  • Large files: Use response.iter_content(chunk_size=1024) to bite off what you can chew.
  • Caching: Like squirrels 🐿️, stash your fetched images to reduce server load and quicken future retrievals.
  • Concurrency: Clone yourself á la Dr.Stange with Python's ThreadPoolExecutor for download multiverse exploration!

Jupyter/IPython printers: direct display

For the folks living in the Jupyter universe, here's your special weapon for direct image display:

from IPython.display import Image, display display(Image(url='YOUR_IMAGE_URL')) # Just-Jupyter-Things: One wand wave, image appears!

The display function coupled with Image from IPython.display, you can wave your wand and have the image rendered in your notebook!