
If you’re developing or designing a website, you probably need to get hold of some stock images. They can be helpful for prototyping, or even to use in your production app.
You can easily build a random image fetcher using the ever-friendly Python language. You can use it to showcase random visuals in a widget, test for resolution switching, or show off a product recommendation engine.
Follow this project to gain hands-on experience with the Requests and Pillow module. They will prove useful for future web work, including image processing.
The Requests and Pillow Modules
The Requests module makes it simple to make HTTP requests and returns a response object that contains data such as encoding, and status. With this, you can develop many interesting applications such as a website status checker, web scraper, stock market monitor bot, and website performance tester. To install the Requests module, open the terminal and type:
pip install requests
The Pillow library—a fork of the Python Imaging Library (PIL)—provides image processing capabilities that help in editing, creating, converting file formats, and saving images. It offers broad file format compatibility and a useful internal representation. To install the Pillow module, open the terminal and type:
pip install Pillow
How to Build a Random Image Fetcher Using Python
You can find the source code of Random Image Fetcher using Python in this GitHub Repository.
Import the modules and define a function named img_requests() that takes txt as an input parameter. Send a GET method to Unsplash’s API URL and use the format method to fill in the placeholder, {0}, with the value of txt. Save the response of the content in JPG format and open the image so that the user can view it. Finally, close the opened file.
import requests
from PIL import Imagedef img_requests(txt):
response = requests.get("https://source.unsplash.com/random{0}".format(txt))
file = open('image.jpg', 'wb')
file.write(response.content)
img = Image.open(r"image.jpg")
img.show()
file.close()
Display the different options the program provides for the user. The first four options will fetch an image in HD, Full HD, 2K, or 4K resolution depending on the choice. If the user chooses the fifth option, he has to provide a keyword. Based on it, the program will select a suitable image and save it to the system.
print("""Please provide an option for Image
1. HD Random Picture
2. FHD Random Picture
3. 2K Random Picture
4. 4k Random Picture
5. Picture with User Provided Keyword """)
Get the user’s choice, display an appropriate message, and call the img_requests function, passing the appropriate text for their query.
ans = input()if 'one' in ans or '1' in ans:
print("Please wait while we fetch an HD image.")
img_requests('/1280x720')
elif 'two' in ans or '2' in ans:
print("Please wait while we fetch a Full HD image.")
img_requests('/1920x1080')
elif 'three' in ans or '3' in ans:
print("Please wait while we fetch a 2k image.")
img_requests('/2048x1080')
elif 'four' in ans or '4' in ans:
print("Please wait while we fetch a 4k image.")
img_requests('/4096x2160')
The fifth option is a bit more complicated. If the user chooses it, ask them to enter their keywords. Add a question mark in front of the keyword and call the function to fetch a random image according to the input.
elif 'five' in ans or '5' in ans:
print("Please enter a keyword you want to get a random image of.")
st = input()
st = "?" + st
print("Please wait while we fetch the images from our database.")
img_requests(st)
If the user enters anything else, ask them to provide valid input:
else:
print("Please provide a valid input.")
Put all the code together and enjoy fetching random pictures in high resolution.
Output of the Random Image Fetcher
On running the program above, the program displays five options. On choosing any of the options, the program saved an image and displays it on the screen.
If you choose option 5 and enter the keyword Spider-Man, the program fetched the following Spider-Man image from Unsplash.
Web Scraping Using Python
Many sites provide useful APIs, like Unsplash’s random image fetcher. But for those that don’t, you can always resort to web scraping, and the Requests module can help.
Other useful modules include Beautiful Soup, Selenium, Scrapy, Urllib, and Mechanize. You can use web scraping to extract information from any website, store it, and analyze it according to your requirements.
Some of the applications you can develop using this technique include a news scraper, a price tracker, and an image downloader. Web Scraping is also extensively used in Natural Language Processing to train models and perform sentiment analysis.