python实现图片批量压缩程序

yipeiwu_com5年前Python基础

 本文实例为大家分享了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基于pygame实现响应游戏中事件的方法(附源码)

python基于pygame实现响应游戏中事件的方法(附源码)

本文实例讲述了python基于pygame实现响应游戏中事件的方法。分享给大家供大家参考,具体如下: 先看一下我做的demo效果: 当玩家按下键盘上的:上,下,左,右键的时候,后台会打...

今天 平安夜 Python 送你一顶圣诞帽 @微信官方

今天 平安夜 Python 送你一顶圣诞帽 @微信官方

还有多少耿直boy和我一样在等待微信官方送上一顶圣诞帽? 最后知道真相的我眼泪掉下来…… (还蒙在鼓里的同学请在微信最上方的搜索栏自行搜索『圣诞帽』) 好吧,你不给,咱自己来,不就...

解决python 文本过滤和清理问题

问题 某些无聊的脚本小子在Web页面表单中填入了“pýtĥöñ”这样的文本,我们想以某种方式将其清理掉。 解决方案 文本过滤和清理所涵盖的...

python绘制铅球的运行轨迹代码分享

python绘制铅球的运行轨迹代码分享

我们按照面向过程程序设计的思想,使用python编写了程序,追踪铅球在运行过程中的位置信息。下面,修改程序代码,导入turtle模块,将铅球的运行轨迹绘制出来。 python3代码如下...

PyQt5 在label显示的图片中绘制矩形的方法

PyQt5 在label显示的图片中绘制矩形的方法

在利用QT编写GUI程序时经常需要一些交互操作,常见的有鼠标事件、键盘事件等。今天我们要实现的是在label中已经显示的图像中绘制矩形框,以便进行下一步操作(如放大细节,选中感兴趣区域等...