前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3 使用pli优化图片,相机或手机拍图片根据exif旋转、纠正方向

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

原创
作者头像
Mos
修改2020-05-27 18:13:36
8310
修改2020-05-27 18:13:36
举报
文章被收录于专栏:菜鸟手记菜鸟手记

首先安装

代码语言:javascript
复制
pip install pillow

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

代码语言:javascript
复制
python -m pip install --upgrade pip

或者

代码语言:javascript
复制
pip install --upgrade pip

那么写个方法

代码语言:javascript
复制
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
代码语言:javascript
复制
compress_image(infile, outfile='', kb=3200, step=5, quality=80)
infile : 原始图片路径
outfile: 生成图片保存路径
kb     : 图片压缩上限,单位kb
step   : 每次压缩质量,
quality: 图片质量,jpg特有,最高为100的质量

使用

代码语言:javascript
复制
small_path = compress_image(image_path)
if not small_path:
small_path = image_path

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

代码语言:javascript
复制
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)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
图片处理
图片处理(Image Processing,IP)是由腾讯云数据万象提供的丰富的图片处理服务,广泛应用于腾讯内部各产品。支持对腾讯云对象存储 COS 或第三方源的图片进行处理,提供基础处理能力(图片裁剪、转格式、缩放、打水印等)、图片瘦身能力(Guetzli 压缩、AVIF 转码压缩)、盲水印版权保护能力,同时支持先进的图像 AI 功能(图像增强、图像标签、图像评分、图像修复、商品抠图等),满足多种业务场景下的图片处理需求。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档