python實(shí)現(xiàn)圖片批量壓縮程序
更新時(shí)間:2018年07月23日 11:48:36 作者:lannooooooooooo
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)圖片批量壓縮程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了python實(shí)現(xiàn)圖片批量壓縮程序的具體代碼,供大家參考,具體內(nèi)容如下
說明
- 運(yùn)行環(huán)境:Win10 Pycharm
- 程序沒有用到面向?qū)ο缶幊谭椒?,只是簡單的面向過程設(shè)計(jì)
- 用到的模塊:PIL、os、sys
- 使用方法: 在Pycharm的terminal中輸入”python xxx.py source_dir dest_dir”就可以把source_dir中的圖片文件進(jìn)行壓縮并保存到dest_dir中
源碼
from PIL import Image
import os
import sys
# 定義可以識別的圖片文件類型,可以自行擴(kuò)充
valid_file_type = ['.jpg', '.png']
# 定義壓縮比,數(shù)值越大,壓縮越小
SIZE_normal = 1.0
SIZE_small = 1.5
SIZE_more_small = 2.0
def make_directory(directory):
"""創(chuàng)建目錄"""
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對圖片進(jìn)行壓縮,還可以改變寬高數(shù)值進(jìn)行壓縮"""
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!"
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用NumPy讀取MNIST數(shù)據(jù)的實(shí)現(xiàn)代碼示例
這篇文章主要介紹了使用NumPy讀取MNIST數(shù)據(jù)的實(shí)現(xiàn)代碼示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
django queryset 去重 .distinct()說明
這篇文章主要介紹了django queryset 去重 .distinct()說明,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Yolov5多邊形標(biāo)簽和JSON數(shù)據(jù)格式轉(zhuǎn)換
通過labelme對圖進(jìn)行標(biāo)注后,得到的是json文件,而Yolov5對數(shù)據(jù)進(jìn)行模型構(gòu)建的時(shí)候,讀取需要的是txt格式的文件。所以需要先通過Python進(jìn)行文件格式的轉(zhuǎn)換,需要的朋友可以參考下2023-05-05
python使用openpyxl實(shí)現(xiàn)對excel表格相對路徑的超鏈接的創(chuàng)建方式
這篇文章主要介紹了python使用openpyxl實(shí)現(xiàn)對excel表格相對路徑的超鏈接的創(chuàng)建方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03

