How to download an image from a URL in Python

How to download an image from a URL in Python

To download an image (or any file) from a URL in Python, you can use the popular requests library. If you haven't already installed it, you can do so with pip:

pip install requests 

Once installed, here's a simple way to download an image:

import requests def download_image(url, filename): response = requests.get(url, stream=True) response.raise_for_status() with open(filename, 'wb') as file: for chunk in response.iter_content(chunk_size=8192): file.write(chunk) # Example usage: url = "https://example.com/path/to/image.jpg" filename = "local_image.jpg" download_image(url, filename) 

Here's a breakdown of what's happening:

  1. The requests.get function fetches the content at the specified URL.
  2. The stream=True parameter ensures that the response is treated as a stream, enabling you to download large files without loading the entire file into memory.
  3. The response.iter_content(chunk_size=8192) method lets you iterate over the response data in chunks (8KB in this case), which is efficient for large files.
  4. The chunks are then written to a local file.

Remember to handle exceptions in production code to account for potential issues like timeouts, non-responsive servers, or other network-related problems.


More Tags

mysql-udf pentaho-data-integration angular-material-7 keycloak relational-algebra logical-operators laravel-3 mariasql wicket psycopg2

More Programming Guides

Other Guides

More Programming Examples