国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現圖片批量壓縮程序

2020-01-04 14:43:35
字體:
來源:轉載
供稿:網友

本文實例為大家分享了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!"

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 济阳县| 宁蒗| 澄迈县| 天峻县| 芷江| 双江| 梁平县| 长沙县| 平顺县| 蒙阴县| 海丰县| 巧家县| 水城县| 安岳县| 千阳县| 湘阴县| 浦江县| 时尚| 仲巴县| 襄汾县| 紫阳县| 柯坪县| 乐昌市| 图木舒克市| 潼南县| 昆山市| 湄潭县| 云浮市| 甘肃省| 云安县| 林甸县| 扶余县| 新巴尔虎右旗| 腾冲县| 富顺县| 通河县| 衡南县| 武功县| 凯里市| 武定县| 衡南县|