In this article, we will see how to download an image in Python using the URLlib.
let’s first import the URLlib library. After importing the library, we can use the function urlretrieve() to download a file from the URL and save it locally.
Following is the example of how to use the urlretrieve()
import urllib.request
url = 'https://example.com/image.jpg'
filename = 'image.jpg'
urllib.request.urlretrieve(url, filename)
In the above example, we first define the URL of the image we want to download, and the filename
with which we want to save the downloaded file.
We pass the above two values as a parameter to the urlretrieve() to download the image and save it to the local filesystem with a specified filename.
Please note that, urlretrieve()
blocks the flow until the download is complete. This can take a while if the image is large or the server is slow. If you need to download multiple images, consider using the Python threading
module to download them in parallel.
Resize the image using Pillow:
After downloading the image, if we want to perform operations such as resizing or cropping we can use the image processing library like Pillow.
Following is the example:
import urllib.request
from PIL import Image
url = 'https://example.com/image.jpg'
filename = 'image.jpg'
urllib.request.urlretrieve(url, filename)
with Image.open(filename) as img:
img = img.resize((640, 480))
img.save('resized_image.jpg')
In the above example, we first download the image using urlretrieve()
as before. We then open the image using Pillow
‘s Image.open()
function, and resize it to a width of 640 pixels and a height of 480 pixels using the resize()
method. Finally, we save the resized image to a new file using the save()
method.