Python實現批量壓縮圖片,

來源:互聯網
上載者:User

Python實現批量壓縮圖片,

本文為大家分享了Python實現批量壓縮圖片的具體代碼,供大家參考,具體內容如下

# -*- coding: utf-8 -*- """ __author__= 'Du' __creation_time__= '2018/1/5 10:06' """  import os from PIL import Image import glob  DIR = 'C:/Users/Public/Pictures/Sample Pictures/'  class Compress_Picture(object):   def __init__(self):     # 圖片格式,可以換成.bpm等     self.file = '.jpg'    # 圖片壓縮批處理   def compressImage(self):     for filename in glob.glob('%s%s%s' % (DIR, '*', self.file)):       # print(filename)       # 開啟原圖片壓縮       sImg = Image.open(filename)       w, h = sImg.size       print(w, h)       dImg = sImg.resize((200, 200), Image.ANTIALIAS) # 設定壓縮尺寸和選項,注意尺寸要用括弧        # 如果不存在目的目錄則建立一個       comdic = "%scompress/"%DIR       if not os.path.exists(comdic):         os.makedirs(comdic)        # 壓縮圖片路徑名稱       f1 = filename.split('/')       f1 = f1[-1].split('\\')       f2 = f1[-1].split('.')       f2 = '%s%s1%s'%(comdic, f2[0], self.file)       # print(f2)       dImg.save(f2) # save這個函數後面可以加壓縮編碼選項JPEG之類的       print("%s compressed succeeded"%f1[-1])   if __name__ == "__main__":   obj = Compress_Picture()   obj.compressImage() 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.