Skip to content

Instantly share code, notes, and snippets.

Last active March 1, 2023 05:47
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
A python script to download image from the url supplied. It checks if the given url is valid image or not.
#!/usr/bin/env python3
# Author: Mahendra Yadav(userimack)
# Run the script using the following command:
# Python3 <image url>
# For example:
# Python3 ''
# Output:
# Image type detected: png
# Success: Image is saved with name: main-dgp.png
import requests
import re
import os
import sys
import imghdr
from time import gmtime, strftime
def check_for_image(response):
if 'image' in response.headers['Content-Type']:
image_type = imghdr.what('', response.content) # Using imaghdr module to verify the signature of the image
if image_type:
print("Image type detected: {0}".format(image_type))
return True
print("Error: Unable to verify the signature of the image")
return False
def get_image(url):
response = requests.get(url)
print("Error: While requesting url: {0}".format(url))
if response:
if check_for_image(response):
extension = os.path.basename(response.headers['Content-Type'])
if 'content-disposition' in response.headers:
content_disposition = response.headers['content-disposition']
filename = re.findall("filename=(.+)", content_disposition)
elif url[-4:] in ['.png', '.jpg', 'jpeg', '.svg']:
filename = os.path.basename(url)
filename = 'image_{0}{1}'.format(strftime("%Y%m%d_%H_%M_%S", gmtime()), '.' + str(extension))
with open(filename, 'wb+') as wobj:
print("Success: Image is saved with name: {0}".format(filename))
print("Sorry: The url doesn't contain any image :(")
if __name__ == '__main__':
if len(sys.argv) < 1:
print("Error: No arguments supplied. Please give the url as arguments\nRun the script as:\npython3 <some_url>")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment