您现在的位置是:首页 > 文章详情

Python3 使用pli优化图片大小,相机或手机拍图片根据exif旋转、纠正方向

日期:2020-05-26点击:549

首先安装

pip install pillow

如果报错,请根据报错的信息去搜索一下,一般都能得到解决,未找到请升级pip

python -m pip install --upgrade pip

或者

pip install --upgrade pip

那么写个方法

from PIL import Image,ExifTags #定义保存图片都路径 def get_outfile(infile, outfile): if outfile: return outfile dir, suffix = os.path.splitext(infile) outfile = '{}-cover{}'.format(dir, suffix) return outfile #缩小图片大小,保持原始宽高 def compress_image(infile, outfile='', kb=3200, step=5, quality=80): o_size = os.path.getsize(infile) / 1024 if o_size <= kb: return False outfile = self.get_outfile(infile, outfile) while o_size > kb: img = Image.open(infile) #相机或手机拍摄图片需要根据exif旋转角度 try: for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break exif = dict(img._getexif().items()) if exif[orientation] == 3: img = img.rotate(180, expand=True) elif exif[orientation] == 6: img = img.rotate(270, expand=True) elif exif[orientation] == 8: img = img.rotate(90, expand=True) except: pass img.save(outfile, quality=quality) if quality - step < 0: break quality -= step o_size = os.path.getsize(outfile) / 1024 return outfile
compress_image(infile, outfile='', kb=3200, step=5, quality=80) infile : 原始图片路径 outfile: 生成图片保存路径 kb : 图片压缩上限,单位kb step : 每次压缩质量, quality: 图片质量,jpg特有,最高为100的质量

使用

small_path = compress_image(image_path) if not small_path: small_path = image_path

在某个项目中用到,就记录一下吧~特别是碰到图片上传后改变了方向的,特别郁闷,所以找到了解决方案

img = Image.open(infile) #相机或手机拍摄图片需要根据exif旋转角度 try: for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break exif = dict(img._getexif().items()) if exif[orientation] == 3: img = img.rotate(180, expand=True) elif exif[orientation] == 6: img = img.rotate(270, expand=True) elif exif[orientation] == 8: img = img.rotate(90, expand=True) except: pass img.save(outfile, quality=100)
原文链接:https://yq.aliyun.com/articles/762733
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章