首先安装
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)