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