Last active
June 2, 2019 03:59
-
-
Save guerbai/3871510956c074b383b433c50e549003 to your computer and use it in GitHub Desktop.
网上下载图片并压缩
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def __get_proper_size_pic_from_url(url, uplimit, workbench=tempfile.mkdtemp(), pic_name=str(time.time()*1000000)): | |
pic_loc = os.path.join(workbench, pic_name+'.'+url.split('.')[-1]) | |
r = requests.get(url, stream=True) | |
if r.status_code == 200: | |
with open(pic_loc, 'wb') as f: | |
r.raw.decode_content = True | |
shutil.copyfileobj(r.raw, f) | |
else: | |
logger.warning('download pic failed with url {0}'.format(url)) | |
return | |
pic_size = os.stat(pic_loc).st_size | |
quality = 75 | |
while pic_size > uplimit: | |
im = Image.open(pic_loc) | |
# quality = int(math.sqrt(uplimit/(pic_size+1024*100))*100) | |
pic_name = pic_name+'_compressed' | |
pic_loc = os.path.join(workbench, pic_name+'.'+url.split('.')[-1]) | |
im.save(pic_loc, quality=quality) | |
im.close() | |
quality = int(quality/2) | |
pic_size = os.stat(pic_loc).st_size | |
print os.stat(pic_loc).st_size | |
return pic_loc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment