python调整图片大小不覆盖exif_Python3 使用pli优化图片大小,相机或手机拍图片根据exif旋转、纠正方向-阿里云开发者社区...

首先安装

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值