Uploading images from a URL is a common requirement in many Python applications, from data scraping to automating social media posts.
Just yesterday I was tinkering with tkinter (get it?) and I wanted to display a few images in my GUI. Of course, I could just download the image and put it in the right folder. But that’s too static for a language as dynamic as Python, no?
You can use images from a URL in your Python code with the help of two essential libraries: “requests” for downloading images and “Pillow” for optional image processing.
To begin, ensure that you have Python installed on your system. Additionally you need to install the “Pillow” and “requests” libraries which can be done using pip commands:
pip install pillow pip install requests
If you want to read up on these two amazing libraries, here are the documentations for pillow and requests.
Uploading Images Online Using Python
1. Uploading Images Online with Modification
Import necessary libraries before starting the code.
from PIL import Image import requests
Open the image file and make the necessary modifications / optimizations using the Pillow library.
# Open the image file with Image.open("image.jpg") as img: # Perform image operations, e.g., resize img = img.resize((800, 600), Image.ANTIALIAS) # Save to a byte stream img_byte_arr = io.BytesIO() img.save(img_byte_arr, format='JPEG') img_data = img_byte_arr.getvalue()
3: Set up a POST request and send the image for upload.
# Setup the POST request url = "<https://example.com/image-upload>" # URL of the API for uploading image headers = {"Authorization": "Client-ID"} files = {"image": ("image.jpg", img_data, 'image/jpeg')} # Send the POST request response = requests.post(url, headers=headers, files=files)
4: Check for any errors and report them to the terminal.
# Check the response if response.status_code == 201: print("Image uploaded successfully!") else: print("Image wasn't uploaded.")
2. Uploading Images Online without Modification
If you don’t want to modify the image and upload it as-is, follow steps 1, 3 and 4. And skip modifying the file in step 2. Here’s how the code will look:
from PIL import Image import requests # Open the image file with Image.open("image.jpg") as img_file: # Perform image operations, e.g., resize img = img_file.read() # Setup the POST request url = "<https://example.com/image-upload>" headers = {"Authorization": "Client-ID"} files = {"image": ("image.jpg", img_data)} # Send the POST request response = requests.post(url, headers=headers, files=files) # Check the response if response.status_code == 201: print("Image uploaded successfully!") else: print("Image wasn't uploaded.")
3. When to Use the Pillow Library?
As you have seen, you can upload images without using the Pillow library. So, why even use it?
- Modify the Image: Pillow is an essential tool if any image manipulation is required before upload, such as resizing, format conversion, color adjustments, or adding watermarks.
- Optimize File Size: Pillow can be used to compress images or change their format (e.g., converting a PNG to a JPEG), significantly reducing the server’s upload time and storage space.
- Validate Image Content: Before uploading, you might want to verify certain aspects of an image (e.g., dimensions, aspect ratio) to ensure they meet specific criteria.
You can read more on the Pillow documentation page.
Downloading & Using Online Images in Python Code
1. urllib.request
import urllib.request # Specify the image URL and the appropriate headers. url = "<https://example.com/wp-content/uploads/image.jpg>" headers = {'User-Agent': 'Mozilla/5.0’} # Create a request object to call the servers. req = urllib.request.Request(url, headers=headers) # Open the URL to download the image and read its response. with urllib.request.urlopen(req) as response: with open("image.jpg", 'wb') as f: # Open the image file in write mode (binary) f.write(response.read()) # Write the response, i.e., the requested image
2. Requests
import urllib.request # Specify the image URL and the appropriate headers. url = "<https://example.com/wp-content/uploads/image.jpg>" headers = {'User-Agent': 'Mozilla/5.0’} # Create a request object to call the servers. req = urllib.request.Request(url, headers=headers) # Open the URL to download the image and read its response. with urllib.request.urlopen(req) as response: with open("image.jpg", 'wb') as f: # Open the image file in write mode (binary) f.write(response.read()) # Write the response, i.e., the requested image
3. Urllib.request vs Requests: Which one should you use?
urllib.request is part of Python’s standard library, meaning it’s built into Python and does not require additional installation. It provides a lower-level interface for making HTTP requests and handling responses.
This can sometimes require more code to perform tasks that are otherwise straightforward in requests. However, it also means that the higher-level interface (requests) can be slower than urllib.requests.
Simply put, ‘requests’ is typically the better choice if your application requires complex HTTP communication. However, if you prefer not to add external dependencies or your needs are very basic, go with ‘urllib.request’.
Creating URLs for Desired Images
When you have an image you want to use in your Python code or share online, generating a shareable URL is a key step. Here’s how to do this:
1. Cloud Storage Services
Both Google Drive and Microsoft OneDrive provide a reliable and secure way to upload your images and generate URLs that can be embedded in applications.
1. Upload the Image: Drag your image file to the browser where you have your cloud storage open, or use the “New” button (Google Drive) or “Upload” button (OneDrive) to upload it manually.
2. Get Shareable Link: Right-click the file and select “Get shareable link” or “Share.” Adjust the settings to allow anyone with the link to view it.
3. Copy and Use the URL: Copy the generated link to use in your Python script or share it.
2. Dropbox
Dropbox is another excellent option for hosting images with the benefit of generating direct links easily.
1. Upload the Image: Use the Dropbox app or website to upload your image.
2. Create a Link: Right-click the uploaded file and choose “Copy Dropbox Link.”
3. Modify the Link for Direct Access: Change the end of the URL from “?dl=0” to “?raw=1” to ensure the link directs to the image itself rather than a download page.
3. Content Hosting Sites
Imgur is popular for quick image uploads without needing an account.
Go to Imgur.com and click “New post.” You can upload your image without signing in. Once uploaded, Imgur will display the image with a direct URL, which you can copy.
Flickr is famous among photographers and those who need high-quality image hosting with powerful sharing and management features.
After creating an account, use the “Upload” option to add your image to Flickr. Ensure the image privacy is set to “Public” and copy the URL that can be used in your code.
4. Image Hosting for Developers
If your project is already using GitHub, you can also use it to host images.
1. Upload the Image: Add your image to your repository by pushing via Git or uploading directly on the GitHub site.
2. Get the URL: View the file in the repository, right-click the image, and select “Copy image address.”