def download(url, ext : str = "jpg", sizeLimit : int = 8000000, ua : str = 'CorpNewt DeepThoughtBot'):
"""Download the passed URL and return the file path."""
# Set up a temp directory
dirpath = tempfile.mkdtemp()
tempFileName = url.rsplit('/', 1)[-1]
# Strip question mark
tempFileName = tempFileName.split('?')[0]
imagePath = dirpath + "/" + tempFileName
try:
rImage = requests.get(url, stream = True, headers = {'User-agent': ua})
except:
remove(dirpath)
return None
with open(imagePath, 'wb') as f:
for chunk in rImage.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
# Check if the file exists
if not os.path.exists(imagePath):
remove(dirpath)
return None
# Let's make sure it's less than the passed limit
imageSize = os.stat(imagePath)
while int(imageSize.st_size) > sizeLimit:
try:
# Image is too big - resize
myimage = Image.open(imagePath)
xsize, ysize = myimage.size
ratio = sizeLimit/int(imageSize.st_size)
xsize *= ratio
ysize *= ratio
myimage = myimage.resize((int(xsize), int(ysize)), Image.ANTIALIAS)
myimage.save(imagePath)
imageSize = os.stat(imagePath)
except Exception:
# Image too big and can't be opened
remove(dirpath)
return None
try:
# Try to get the extension
img = Image.open(imagePath)
ext = img.format
img.close()
except Exception:
# Not something we understand - error out
remove(dirpath)
return None
if ext:
os.rename(imagePath, '{}.{}'.format(imagePath, ext))
return '{}.{}'.format(imagePath, ext)
else:
return imagePath
评论列表
文章目录