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 continue语句用法实例
Mar 11 Python
Python探索之ModelForm代码详解
Oct 26 Python
python中的随机函数random的用法示例
Jan 27 Python
python3射线法判断点是否在多边形内
Jun 28 Python
浅谈Python 递归算法指归
Aug 22 Python
分享8点超级有用的Python编程建议(推荐)
Oct 13 Python
django框架ModelForm组件用法详解
Dec 11 Python
python使用正则来处理各种匹配问题
Dec 22 Python
Python csv文件记录流程代码解析
Jul 16 Python
flask开启多线程的具体方法
Aug 02 Python
python中strip(),lstrip(),rstrip()函数的使用讲解
Nov 17 Python
python自动从arxiv下载paper的示例代码
Dec 05 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
收音机发烧友应当熟知的100条知识
2021/03/02 无线电
PHP表单验证的3个函数ISSET()、empty()、is_numeric()的使用方法
2011/08/22 PHP
php自定义apk安装包实例
2014/10/20 PHP
thinkPHP中多维数组的遍历方法
2016/01/09 PHP
Zend Framework分发器用法示例
2016/12/11 PHP
php利用imagemagick实现复古老照片效果实例
2017/02/16 PHP
原生php实现excel文件读写的方法分析
2018/04/25 PHP
解决Laravel 不能创建 migration 的问题
2019/10/09 PHP
JS中不为人知的五种声明Number的方式简要概述
2013/02/22 Javascript
Js操作树节点自动折叠展开的几种方法
2014/05/05 Javascript
jQuery插件之Tocify动态节点目录菜单生成器附源码下载
2016/01/08 Javascript
JS实现把鼠标放到链接上出现滚动文字的方法
2016/04/06 Javascript
AngularJS中的过滤器filter用法完全解析
2016/04/22 Javascript
详解基于Node.js的微信JS-SDK后端接口实现代码
2017/07/15 Javascript
webpack里使用jquery.mCustomScrollbar插件的方法
2018/05/30 jQuery
关于微信公众号开发无法支付的问题解决
2018/12/28 Javascript
elementUI select组件使用及注意事项详解
2019/05/29 Javascript
Javascript地址引用代码实例解析
2020/02/25 Javascript
JS图片预加载三种实现方法解析
2020/05/08 Javascript
40行代码把Vue3的响应式集成进React做状态管理
2020/05/20 Javascript
jQuery使用jsonp实现百度搜索的示例代码
2020/07/08 jQuery
在 Django/Flask 开发服务器上使用 HTTPS
2014/07/03 Python
Pandas之排序函数sort_values()的实现
2019/07/09 Python
postman模拟访问具有Session的post请求方法
2019/07/15 Python
Django如何使用第三方服务发送电子邮件
2019/08/14 Python
pycharm设置python文件模板信息过程图解
2020/03/10 Python
Python selenium环境搭建实现过程解析
2020/09/08 Python
Roxy美国官网:澳大利亚冲浪、滑雪健身品牌
2016/07/30 全球购物
次世代生活态度:Hypebeast
2018/07/05 全球购物
彪马俄罗斯官网:PUMA俄罗斯
2019/07/13 全球购物
传统软件工程与面向对象的软件工程有什么区别
2012/05/31 面试题
中层干部竞聘演讲稿
2014/05/15 职场文书
小学兴趣小组活动总结
2014/07/07 职场文书
史上最牛辞职信
2015/05/13 职场文书
K8s部署发布Golang应用程序的实现方法
2021/07/16 Golang
python如何为list实现find方法
2022/05/30 Python