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使用两种发邮件的方式smtp和outlook示例

smtp是直接调用163邮箱的smtp服务器,需要在163邮箱中设置一下。outlook发送就是Python直接调用win32方式。调用程序outlook直接发送邮件。 impor...

python实现归并排序算法

归并排序是典型的分治法的应用 思想:先递归分解数组,再合并数组 原理:将数组分解最小之后,然后合并两个有序数组,基本思想是比较两个数组的最前面的数,谁小就取谁,取完后,将相应的指针后移以...

python调用staf自动化框架的方法

1、配置环境 支持python2和python3 On Linux, Solaris, or FreeBSD, add the /usr/local/staf/lib directory...

django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t exist”)问题的解决

django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t exist”)问题的解决

一、现象 最近在数据库中删除了一张表,重新执行python manage.py migrate时出错,提示不存在这张表。通过查找相关的资料,最后找到了相关的解决方法,下面话不多说了,来一...

安装好Pycharm后如何配置Python解释器简易教程

安装好Pycharm后如何配置Python解释器简易教程

这两天有许多Python小白加入学习群,并且问了许多关于Pycharm基本使用的问题,今天小编就以配置Python解释器的问题给大家简单絮叨一下。 1、一般来说,当我们启动Pycharm...