python实现图片批量压缩程序


Posted in Python onJuly 23, 2018

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

说明

  • 运行环境:Win10 Pycharm
  • 程序没有用到面向对象编程方法,只是简单的面向过程设计
  • 用到的模块:PIL、os、sys
  • 使用方法: 在Pycharm的terminal中输入”python xxx.py source_dir dest_dir”就可以把source_dir中的图片文件进行压缩并保存到dest_dir中

源码

from PIL import Image
import os
import sys

# 定义可以识别的图片文件类型,可以自行扩充
valid_file_type = ['.jpg', '.png']
# 定义压缩比,数值越大,压缩越小
SIZE_normal = 1.0
SIZE_small = 1.5
SIZE_more_small = 2.0


def make_directory(directory):
  """创建目录"""
  os.makedirs(directory)


def directory_exists(directory):
  """判断目录是否存在"""
  if os.path.exists(directory):
    return True
  else:
    return False


def list_img_file(directory):
  """列出目录下所有文件,并筛选出图片文件列表返回"""
  old_list = os.listdir(directory)
  # print old_list
  new_list = []
  for filename in old_list:
    if os.path.isfile(filename):
      f, e = os.path.splitext(filename)
      if e in valid_file_type:
        new_list.append(filename)
      else:
        pass
    else:
      pass
  # print new_list
  return new_list


def print_help():
  print """
  This program helps compress many image files
  you can choose which scale you want to compress your img(jpg/png/etc)
  1) normal compress(4M to 1M around)
  2) small compress(4M to 500K around)
  3) smaller compress(4M to 300K around)
  """


def compress(choose, des_dir, file_list):
  """压缩算法,img.thumbnail对图片进行压缩,还可以改变宽高数值进行压缩"""
  if choose == '1':
    scale = SIZE_normal
  if choose == '2':
    scale = SIZE_small
  if choose == '3':
    scale = SIZE_more_small
  for infile in file_list:
    img = Image.open(infile)
    # size_of_file = os.path.getsize(infile)
    w, h = img.size
    img.thumbnail((int(w/scale), int(h/scale)))
    img.save(des_dir + '/' + infile)


if __name__ == "__main__":
  src_dir, des_dir = sys.argv[1], sys.argv[2]
  if directory_exists(src_dir):
    if not directory_exists(des_dir):
      make_directory(des_dir)
    # business logic
    file_list = list_img_file(src_dir)
    # print file_list
    if file_list:
      print_help()
      choose = raw_input("enter your choice:")
      compress(choose, des_dir, file_list)
    else:
      pass
  else:
    print "source directory not exist!"

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python和perl实现批量对目录下电子书文件重命名的代码分享
Nov 21 Python
用python实现简单EXCEL数据统计的实例
Jan 24 Python
Python读取指定目录下指定后缀文件并保存为docx
Apr 23 Python
Python之re操作方法(详解)
Jun 14 Python
Python实现公历(阳历)转农历(阴历)的方法示例
Aug 22 Python
Python遍历numpy数组的实例
Apr 04 Python
Python SQL查询并生成json文件操作示例
Aug 17 Python
解决django中ModelForm多表单组合的问题
Jul 18 Python
win10安装tensorflow-gpu1.8.0详细完整步骤
Jan 20 Python
细数nn.BCELoss与nn.CrossEntropyLoss的区别
Feb 29 Python
Python configparser模块封装及构造配置文件
Aug 07 Python
PyTorch中Tensor的数据类型和运算的使用
Sep 03 Python
python中的插值 scipy-interp的实现代码
Jul 23 #Python
Flask框架URL管理操作示例【基于@app.route】
Jul 23 #Python
python中的turtle库函数简单使用教程
Jul 23 #Python
Flask框架配置与调试操作示例
Jul 23 #Python
python实现时间o(1)的最小栈的实例代码
Jul 23 #Python
Flask框架Flask-Principal基本用法实例分析
Jul 23 #Python
Flask框架Flask-Login用法分析
Jul 23 #Python
You might like
php基础学习之变量的使用
2011/06/09 PHP
php在页面中调用fckeditor编辑器的方法
2011/06/10 PHP
PDO版本问题 Invalid parameter number: no parameters were bound
2013/01/06 PHP
浅析十款PHP开发框架的对比
2013/07/05 PHP
PHP读取文件内容的五种方式
2015/12/28 PHP
PHP面向对象五大原则之开放-封闭原则(OCP)详解
2018/04/04 PHP
PHP Redis扩展无法加载的问题解决方法
2019/08/22 PHP
PHP实现单文件、多个单文件、多文件上传函数的封装示例
2019/09/02 PHP
jQuery基础框架浅入剖析
2012/12/27 Javascript
JQuery插件开发示例代码
2013/11/06 Javascript
javascript实现多级联动下拉菜单的方法
2015/02/06 Javascript
canvas学习之API整理笔记(一)
2016/12/29 Javascript
js实现漫天星星效果
2017/01/19 Javascript
基于JavaScript实现焦点图轮播效果
2017/03/27 Javascript
ionic+html5+API实现双击返回键退出应用
2019/09/17 Javascript
JavaScript大数相加相乘的实现方法实例
2020/10/18 Javascript
初步理解Python进程的信号通讯
2015/04/09 Python
windows上安装Anaconda和python的教程详解
2017/03/28 Python
ubuntu中配置pyqt4环境教程
2017/12/27 Python
Python实现的圆形绘制(画圆)示例
2018/01/31 Python
python实现对求解最长回文子串的动态规划算法
2018/06/02 Python
在Python中pandas.DataFrame重置索引名称的实例
2018/11/06 Python
python实现给微信指定好友定时发送消息
2019/04/29 Python
18个Python脚本可加速你的编码速度(提示和技巧)
2019/10/17 Python
Python3.7+tkinter实现查询界面功能
2019/12/24 Python
Sandro Paris美国官网:典雅别致的法国时尚服饰品牌
2017/12/26 全球购物
阿联酋网上花店:Ferns N Petals
2018/02/14 全球购物
电气工程及其自动化学生实习自我鉴定
2013/09/19 职场文书
党支部活动策划方案
2014/08/18 职场文书
收款委托书
2014/10/14 职场文书
技术员岗位职责
2015/02/04 职场文书
前台接待员岗位职责
2015/04/15 职场文书
网络舆情信息简报
2015/07/21 职场文书
学生检讨书范文
2019/06/24 职场文书
让文件路径提取变得更简单的Python Path库
2021/05/27 Python
python自动化测试之Selenium详解
2022/03/13 Python