Python实现批量压缩图片

yipeiwu_com7年前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/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设计】。

相关文章

python文档字符串(函数使用说明)使用详解

python文档字符串(函数使用说明)使用详解

1.效果图: 2.代码: # 文档字符串( doc str) 是 函数使用说明 # 用法: 在函数第一行写一个字符串 def fn(*nums): ''' 函数的作用: 计...

Python set集合类型操作总结

Python中除了字典,列表,元组还有一个非常好用的数据结构,那就是set了,灵活的运用set可以减去不少的操作(虽然set可以用列表代替) 小例子 1.如果我要在许多列表中找出相同的项...

Python实现银行账户资金交易管理系统

Python实现银行账户资金交易管理系统

用类和对象实现一个银行账户的资金交易管理, 包括存款、取款和打印交易详情, 交易详情中包含每次交易的时间、存款或者取款的金额、每次交易后的余额。 如: 下面按照要求定义一个账户 Acc...

Python使用pip安装报错:is not a supported wheel on this platform的解决方法

Python使用pip安装报错:is not a supported wheel on this platform的解决方法

本文讲述了Python使用pip安装报错:is not a supported wheel on this platform的解决方法。分享给大家供大家参考,具体如下: 可能的原因1:安...

python实现名片管理系统项目

python实现名片管理系统项目

名片管理系统,供大家参考,具体内容如下 环境要求:linux系统、python2.x或python3.x 资源地址:GitHub地址 写在前面的话:笔者之前在初学C/C++时,都曾写过类...