python实现图片批量压缩程序

python实现图片批量压缩程序,第1张

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

 本文实例为大家分享了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,file_List)    else:      pass  else:    print "source directory not exist!"

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

您可能感兴趣的文章:Python实现批量压缩图片python中学习K-Means和图片压缩python利用Guetzli批量压缩图片在Python中使用pngquant压缩png图片的教程 总结

以上是内存溢出为你收集整理的python实现图片批量压缩程序全部内容,希望文章能够帮你解决python实现图片批量压缩程序所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1204678.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存