Python使用Pillow庫輕松調(diào)整圖像尺寸
在圖像處理任務(wù)中,調(diào)整圖片大小是一個(gè)常見需求。無論是為網(wǎng)頁優(yōu)化圖片、準(zhǔn)備機(jī)器學(xué)習(xí)數(shù)據(jù)集,還是簡單調(diào)整照片尺寸,Python都提供了簡單高效的解決方案。本文將介紹如何使用流行的Pillow庫(PIL)來輕松實(shí)現(xiàn)圖片縮放。
為什么選擇Pillow庫?
Pillow是Python中最常用的圖像處理庫之一,它是PIL(Python Imaging Library)的一個(gè)友好分支。Pillow具有以下優(yōu)勢:
- 簡單易用的API
- 支持多種圖像格式(JPEG, PNG, BMP, GIF等)
- 豐富的圖像處理功能
- 活躍的社區(qū)支持
安裝Pillow
在開始之前,確保已安裝Pillow庫??梢酝ㄟ^pip快速安裝:
pip install pillow
基本圖片縮放方法
1. 打開圖像并調(diào)整大小
from PIL import Image
def resize_image(input_path, output_path, size):
"""
調(diào)整圖片大小并保存
參數(shù):
input_path: 輸入圖片路徑
output_path: 輸出圖片路徑
size: 目標(biāo)尺寸,格式為(寬度, 高度)
"""
with Image.open(input_path) as img:
# 使用LANCZOS重采樣濾波器(高質(zhì)量)
resized_img = img.resize(size, Image.LANCZOS)
resized_img.save(output_path)
# 使用示例
resize_image("input.jpg", "output.jpg", (800, 600))
2. 按比例縮放圖片
有時(shí)我們需要保持寬高比,只指定一個(gè)維度:
def resize_with_aspect_ratio(input_path, output_path, max_size):
"""
按比例調(diào)整圖片大小,保持寬高比
參數(shù):
input_path: 輸入圖片路徑
output_path: 輸出圖片路徑
max_size: 最大寬度或高度
"""
with Image.open(input_path) as img:
width, height = img.size
# 計(jì)算縮放比例
if width > height:
new_width = max_size
new_height = int(height * (max_size / width))
else:
new_height = max_size
new_width = int(width * (max_size / height))
resized_img = img.resize((new_width, new_height), Image.LANCZOS)
resized_img.save(output_path)
# 使用示例:將圖片最大邊調(diào)整為500像素
resize_with_aspect_ratio("input.jpg", "output_scaled.jpg", 500)
高級縮放選項(xiàng)
1. 使用不同的重采樣濾波器
Pillow提供了多種重采樣濾波器,影響縮放質(zhì)量:
Image.NEAREST: 最近鄰濾波(速度快,質(zhì)量低)Image.BOX: 盒式濾波Image.BILINEAR: 雙線性濾波Image.HAMMING: Hamming濾波Image.BICUBIC: 雙三次濾波Image.LANCZOS: Lanczos重采樣(高質(zhì)量,推薦)
# 使用不同濾波器比較
with Image.open("input.jpg") as img:
# 低質(zhì)量快速縮放
fast_resize = img.resize((200, 200), Image.NEAREST)
fast_resize.save("fast_resize.jpg")
# 高質(zhì)量縮放
high_quality = img.resize((200, 200), Image.LANCZOS)
high_quality.save("high_quality.jpg")
2. 批量縮放圖片
import os
from PIL import Image
def batch_resize_images(input_folder, output_folder, size):
"""
批量縮放文件夾中的所有圖片
參數(shù):
input_folder: 輸入文件夾路徑
output_folder: 輸出文件夾路徑
size: 目標(biāo)尺寸,格式為(寬度, 高度)
"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename)
try:
with Image.open(input_path) as img:
resized_img = img.resize(size, Image.LANCZOS)
resized_img.save(output_path)
print(f"成功處理: {filename}")
except Exception as e:
print(f"處理 {filename} 時(shí)出錯(cuò): {e}")
# 使用示例
batch_resize_images("input_images", "output_images", (800, 600))
實(shí)際應(yīng)用案例
1. 為網(wǎng)頁準(zhǔn)備縮略圖
def create_thumbnail(input_path, output_path, thumbnail_size=128):
"""
創(chuàng)建方形縮略圖
參數(shù):
input_path: 輸入圖片路徑
output_path: 輸出縮略圖路徑
thumbnail_size: 縮略圖邊長(像素)
"""
with Image.open(input_path) as img:
# 先按比例縮放,使較小邊等于縮略圖大小
img.thumbnail((thumbnail_size, thumbnail_size), Image.LANCZOS)
# 創(chuàng)建方形畫布
background = Image.new('RGBA', (thumbnail_size, thumbnail_size), (255, 255, 255, 0))
# 計(jì)算居中位置
offset = ((thumbnail_size - img.size[0]) // 2,
(thumbnail_size - img.size[1]) // 2)
background.paste(img, offset)
background.save(output_path)
# 使用示例
create_thumbnail("product.jpg", "product_thumbnail.png")
2. 調(diào)整圖片大小同時(shí)保持EXIF信息
from PIL import Image, ExifTags
def resize_with_exif(input_path, output_path, size):
"""
調(diào)整圖片大小并保留EXIF信息
參數(shù):
input_path: 輸入圖片路徑
output_path: 輸出圖片路徑
size: 目標(biāo)尺寸,格式為(寬度, 高度)
"""
with Image.open(input_path) as img:
# 獲取EXIF數(shù)據(jù)
exif_data = {}
if hasattr(img, '_getexif'):
exif = img._getexif()
if exif is not None:
for tag, value in exif.items():
decoded = ExifTags.TAGS.get(tag, tag)
exif_data[decoded] = value
# 調(diào)整大小
resized_img = img.resize(size, Image.LANCZOS)
# 保存圖片并寫入EXIF數(shù)據(jù)(僅JPEG支持)
resized_img.save(output_path, exif=exif_data if 'JPEG' in img.format.upper() else None)
# 使用示例
resize_with_exif("photo.jpg", "photo_resized.jpg", (1024, 768))
性能優(yōu)化技巧
- 批量處理:使用
Image.thumbnail()方法可以避免創(chuàng)建中間圖像對象 - 內(nèi)存管理:處理大量圖片時(shí),及時(shí)關(guān)閉圖像對象或使用
with語句 - 多線程處理:對于大量圖片,可以使用
concurrent.futures實(shí)現(xiàn)并行處理 - 選擇合適格式:根據(jù)用途選擇輸出格式(JPEG適合照片,PNG適合圖形)
常見問題解答
Q: 縮放后的圖片質(zhì)量不佳怎么辦?
A: 使用高質(zhì)量的重采樣濾波器如Image.LANCZOS,并確保輸出格式支持高質(zhì)量(如JPEG質(zhì)量參數(shù)設(shè)為95)
Q: 如何保持圖片寬高比不變?
A: 使用thumbnail()方法或手動計(jì)算比例(如本文的resize_with_aspect_ratio函數(shù))
Q: Pillow支持哪些圖像格式?
A: 支持JPEG, PNG, BMP, GIF, TIFF等常見格式,完整列表見官方文檔
總結(jié)
Python的Pillow庫提供了強(qiáng)大而靈活的圖片縮放功能。從簡單的尺寸調(diào)整到復(fù)雜的批量處理,從保持寬高比到創(chuàng)建縮略圖,Pillow都能輕松應(yīng)對。通過選擇合適的重采樣濾波器和優(yōu)化處理流程,你可以在質(zhì)量和性能之間取得良好平衡。
到此這篇關(guān)于Python使用Pillow庫輕松調(diào)整圖像尺寸的文章就介紹到這了,更多相關(guān)Python Pillow調(diào)整圖像尺寸內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python程序員面試題 你必須提前準(zhǔn)備!(答案及解析)
這篇文章主要為大家解析了你必須提前準(zhǔn)備的Python程序員面試題答案,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
anaconda虛擬環(huán)境python?sklearn庫的安裝過程
Anaconda是專注于數(shù)據(jù)分析的Python發(fā)行版本,包含了conda、Python等190多個(gè)科學(xué)包及其依賴項(xiàng),這篇文章主要給大家介紹了關(guān)于anaconda虛擬環(huán)境python?sklearn庫的安裝過程,需要的朋友可以參考下2023-11-11
TensorFlow2.4完成Word2vec詞嵌入訓(xùn)練方法詳解
這篇文章主要為大家介紹了TensorFlow2.4完成Word2vec詞嵌入訓(xùn)練方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
使用python解析xml成對應(yīng)的html示例分享
這篇文章主要介紹了使用python解析xml成對應(yīng)的html示例,需要的朋友可以參考下2014-04-04
如何將PySpark導(dǎo)入Python的放實(shí)現(xiàn)(2種)
這篇文章主要介紹了如何將PySpark導(dǎo)入Python的放實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
Python中如何創(chuàng)建和運(yùn)行異步任務(wù)詳解
這篇文章主要為大家介紹了Python中如何創(chuàng)建和運(yùn)行異步任務(wù)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
python使用PyV8執(zhí)行javascript代碼示例分享
這篇文章主要介紹了python使用PyV8執(zhí)行javascript的小示例,大家參考使用吧2013-12-12

