加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python实现批量压缩图片

发布时间:2020-12-17 07:30:22 所属栏目:Python 来源:网络整理
导读:本文为大家分享了Python实现批量压缩图片的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- """ __author__= 'Du' __creation_time__= '2018/1/5 10:06' """ import os from PIL import Image import glob DIR = 'C:/Users/Public/Pictures/Sam

本文为大家分享了Python实现批量压缩图片的具体代码,供大家参考,具体内容如下

# -*- coding: utf-8 -*- 
""" 
__author__= 'Du' 
__creation_time__= '2018/1/5 10:06' 
""" 
 
import os 
from PIL import Image 
import glob 
 
DIR = 'C:/Users/Public/Pictures/Sample Pictures/' 
 
class Compress_Picture(object): 
  def __init__(self): 
    # 图片格式,可以换成.bpm等 
    self.file = '.jpg' 
 
  # 图片压缩批处理 
  def compressImage(self): 
    for filename in glob.glob('%s%s%s' % (DIR,'*',self.file)): 
      # print(filename) 
      # 打开原图片压缩 
      sImg = Image.open(filename) 
      w,h = sImg.size 
      print(w,h) 
      dImg = sImg.resize((200,200),Image.ANTIALIAS) # 设置压缩尺寸和选项,注意尺寸要用括号 
 
      # 如果不存在目的目录则创建一个 
      comdic = "%scompress/"%DIR 
      if not os.path.exists(comdic): 
        os.makedirs(comdic) 
 
      # 压缩图片路径名称 
      f1 = filename.split('/') 
      f1 = f1[-1].split('') 
      f2 = f1[-1].split('.') 
      f2 = '%s%s1%s'%(comdic,f2[0],self.file) 
      # print(f2) 
      dImg.save(f2) # save这个函数后面可以加压缩编码选项JPEG之类的 
      print("%s compressed succeeded"%f1[-1]) 
 
 
if __name__ == "__main__": 
  obj = Compress_Picture() 
  obj.compressImage() 

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

您可能感兴趣的文章:

  • python中学习K-Means和图片压缩
  • python利用Guetzli批量压缩图片
  • 在Python中使用pngquant压缩png图片的教程

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读