Instantly share code, notes, and snippets.

Embed
What would you like to do?
def download_image(url, download_path):
"""
Downloads a single image from a url to a specific path
:param url: url of image
:param download_path: full path of saved image file
:return: true if successfully downloaded, false otherwise
"""
print "Downloading from " + url
try:
fd = urllib2.urlopen(url, timeout=3)
image_file = io.BytesIO(fd.read())
image = Image.open(image_file)
size = image.size
if size[0] < IMAGE_WIDTH or size[1] < IMAGE_HEIGHT: # Image too small
return False
resized = resizeimage.resize_cover(image, (IMAGE_WIDTH, IMAGE_HEIGHT))
resized.save(download_path, 'jpeg', icc_profile=resized.info.get('icc_profile'))
except (IOError, HTTPException, CertificateError) as e:
print e
return False
# Check if photo meets minimum size requirement
size = os.path.getsize(download_path)
if size < MINIMUM_FILE_SIZE:
os.remove(download_path)
print "Invalid Image: " + url
return False
# Try opening as array to see if there are any errors
try:
load_image_as_array(download_path)
except ValueError as e:
os.remove(download_path)
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment