Python简易图片批量压缩程序
来源:互联网 发布:死亡天使蘑菇 淘宝 编辑:程序博客网 时间:2024/06/06 08:40
Python简易图片疲批量压缩程序
说明
- 运行环境:Win10 Pycharm
- 程序没有用到面向对象编程方法,只是简单的面向过程设计
- 用到的模块:PIL、os、sys
- 使用方法: 在Pycharm的terminal中输入”python xxx.py source_dir dest_dir”就可以把source_dir中的图片文件进行压缩并保存到dest_dir中
源码
from PIL import Imageimport osimport sys# 定义可以识别的图片文件类型,可以自行扩充valid_file_type = ['.jpg', '.png']# 定义压缩比,数值越大,压缩越小SIZE_normal = 1.0SIZE_small = 1.5SIZE_more_small = 2.0def make_directory(directory): """创建目录""" os.makedirs(directory)def directory_exists(directory): """判断目录是否存在""" if os.path.exists(directory): return True else: return Falsedef 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_listdef 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!"
0 0
- Python简易图片批量压缩程序
- 如何用Python智能批量压缩图片?
- 快速批量压缩图片
- Python学习-----Tinypng图片压缩小程序
- 批量下载图片,简易脚本
- python图片简易二值化
- 用批处理批量压缩图片
- Linux下批量压缩图片
- Android图片压缩批量上传
- Android异步批量压缩图片
- 利用Guetzli批量压缩图片
- 用ps批量压缩图片
- 使用tinify批量压缩图片
- java 图片 批量 压缩 +全部压缩
- TinyPng批量压缩Python脚本
- Python学习-----Tinypng图片压缩小程序(2)
- Python批量下载图片
- Python 图片批量裁剪
- [从零开始unity3D]“五子连珠”游戏实现,网格数组的创建(1)
- UVA11100 The Trip, 2007(贪心)
- Java学习笔记之线程
- HDU5120(几何)
- jQuery 之 (二)事件操作、jq对文档的操作、属性选择器使用
- Python简易图片批量压缩程序
- 强悍的javascript手势库
- [2016ICPC 大连网络预选赛] HDU5874 构造
- C++ getline
- C# RichTextBox 滚动条 滚动到最后一行
- 单例模式之个人笔记(一)
- 装饰者模式笔记
- 《将博客搬至CSDN》
- Linux - C预习内容(六)