基于Python實(shí)現(xiàn)一個(gè)圖片壓縮工具
圖片壓縮是在保持圖像質(zhì)量的同時(shí)減小圖像文件大小的過程。這在網(wǎng)絡(luò)應(yīng)用、移動應(yīng)用和網(wǎng)頁設(shè)計(jì)中非常有用,因?yàn)樗梢詼p少加載時(shí)間和存儲空間占用。在本文中,將學(xué)習(xí)如何使用Python來實(shí)現(xiàn)一個(gè)簡單但功能強(qiáng)大的圖片壓縮工具,以及如何在不同情境下進(jìn)行圖片壓縮。
安裝必要的庫
在開始之前,需要安裝兩個(gè)Python庫:Pillow和tqdm。Pillow是一個(gè)強(qiáng)大的圖像處理庫,而tqdm用于顯示壓縮進(jìn)度。
可以使用以下命令來安裝這兩個(gè)庫:
pip install Pillow tqdm
基本的圖片壓縮
首先,將學(xué)習(xí)如何實(shí)現(xiàn)一個(gè)基本的圖片壓縮工具,該工具將圖像的質(zhì)量減小為指定的百分比。將使用Pillow庫來執(zhí)行圖像處理操作。
以下是一個(gè)簡單的圖片壓縮函數(shù):
from PIL import Image import os def compress_image(input_path, output_path, quality=80): """ 壓縮圖片的函數(shù) :param input_path: 輸入圖片文件路徑 :param output_path: 輸出圖片文件路徑 :param quality: 圖片質(zhì)量(0-100),默認(rèn)為80 """ try: # 打開輸入圖片 with Image.open(input_path) as img: # 保存為輸出圖片(JPG格式),設(shè)置質(zhì)量 img.save(output_path, "JPEG", quality=quality) return True except Exception as e: print(f"壓縮圖片時(shí)出錯(cuò):{e}") return False # 示例用法 input_image = "input.jpg" output_image = "output.jpg" compress_image(input_image, output_image, quality=60)
在這個(gè)函數(shù)中,首先使用Pillow庫的Image.open方法打開輸入圖片。然后,使用Image.save方法將圖像保存為JPG格式,并設(shè)置圖像質(zhì)量。較低的質(zhì)量值會導(dǎo)致更大的壓縮比。
批量圖片壓縮
通常,需要批量處理多個(gè)圖片文件。
以下是一個(gè)示例代碼,演示如何批量壓縮多個(gè)圖片文件:
from PIL import Image import os from tqdm import tqdm def batch_compress_images(input_folder, output_folder, quality=80): """ 批量壓縮圖片的函數(shù) :param input_folder: 輸入圖片文件夾路徑 :param output_folder: 輸出圖片文件夾路徑 :param quality: 圖片質(zhì)量(0-100),默認(rèn)為80 """ # 創(chuàng)建輸出文件夾 os.makedirs(output_folder, exist_ok=True) # 獲取輸入文件夾中的所有圖片文件 image_files = [f for f in os.listdir(input_folder) if f.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp'))] for image_file in tqdm(image_files, desc="壓縮進(jìn)度"): try: input_path = os.path.join(input_folder, image_file) output_path = os.path.join(output_folder, image_file) # 壓縮圖片 compress_image(input_path, output_path, quality) except Exception as e: print(f"處理圖片 {image_file} 時(shí)出錯(cuò):{e}") # 示例用法 input_folder = "input_images" output_folder = "output_images" batch_compress_images(input_folder, output_folder, quality=60)
這個(gè)函數(shù)接受輸入圖片文件夾路徑和輸出圖片文件夾路徑,并遍歷輸入文件夾中的所有圖片文件,對每個(gè)文件進(jìn)行壓縮并保存到輸出文件夾中。使用tqdm庫來顯示壓縮進(jìn)度。
自動選擇壓縮質(zhì)量
有時(shí),可能希望自動選擇壓縮質(zhì)量,以便在指定文件大小內(nèi)獲得最佳的圖像質(zhì)量。
以下是一個(gè)示例代碼,演示如何實(shí)現(xiàn)自動選擇壓縮質(zhì)量的功能:
from PIL import Image import os from tqdm import tqdm def auto_compress_images(input_folder, output_folder, target_size_kb): """ 自動選擇壓縮質(zhì)量以達(dá)到目標(biāo)文件大小的函數(shù) :param input_folder: 輸入圖片文件夾路徑 :param output_folder: 輸出圖片文件夾路徑 :param target_size_kb: 目標(biāo)文件大?。↘B) """ # 創(chuàng)建輸出文件夾 os.makedirs(output_folder, exist_ok=True) # 獲取輸入文件夾中的所有圖片文件 image_files = [f for f in os.listdir(input_folder) if f.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp'))] for image_file in tqdm(image_files, desc="壓縮進(jìn)度"): try: input_path = os.path.join(input_folder, image_file) output_path = os.path.join(output_folder, image_file) # 初始化質(zhì)量 quality = 80 # 初始質(zhì)量設(shè)為80 while os.path.getsize(input_path) > target_size_kb * 1024: # 壓縮圖片并保存到臨時(shí)文件 temp_output_path = os.path.join(output_folder, "temp.jpg") compress_image(input_path, temp_output_path, quality) # 用臨時(shí)文件替換原始文件 os.replace(temp_output_path, input_path) # 減小質(zhì)量以進(jìn)一步壓縮 quality -= 10 if quality < 10: break except Exception as e: print(f"處理圖片 {image_file} 時(shí)出錯(cuò):{e}") # 示例用法 input_folder = "input_images" output_folder = "output_images_auto" target_size_kb = 100 # 目標(biāo)文件大小(KB) auto_compress_images(input_folder, output_folder, target_size_kb)
這個(gè)函數(shù)根據(jù)目標(biāo)文件大小自動選擇壓縮質(zhì)量,以便在不超過指定大小的情況下獲得最佳的圖像質(zhì)量。它會不斷嘗試降低質(zhì)量,直到圖像大小小于或等于目標(biāo)大小為止。
總結(jié)
通過本文,學(xué)習(xí)了如何使用Python和Pillow庫來實(shí)現(xiàn)圖片壓縮工具。涵蓋了基本的圖片壓縮、批量圖片壓縮和自動選擇壓縮質(zhì)量等不同情境下的圖片壓縮方法。這個(gè)工具可以幫助大家在不同項(xiàng)目中處理圖片,并根據(jù)需要進(jìn)行壓縮,以便在減小文件大小的同時(shí)保持圖像質(zhì)量。希望這些示例代碼能幫助大家更好地理解和應(yīng)用圖片壓縮技術(shù)。
以上就是基于Python實(shí)現(xiàn)一個(gè)圖片壓縮工具的詳細(xì)內(nèi)容,更多關(guān)于Python圖片壓縮工具的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章

Python數(shù)據(jù)分析matplotlib設(shè)置多個(gè)子圖的間距方法

Docker如何部署Python項(xiàng)目的實(shí)現(xiàn)詳解

python+opencv實(shí)現(xiàn)霍夫變換檢測直線

Python數(shù)據(jù)處理之savetxt()和loadtxt()使用詳解

Python中函數(shù)的多種格式和使用實(shí)例及小技巧

Python實(shí)現(xiàn)數(shù)據(jù)可視化案例分析

python實(shí)現(xiàn)將多個(gè)文件分配到多個(gè)文件夾的方法