最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python使用Pillow庫輕松調(diào)整圖像尺寸

 更新時間:2026年05月11日 08:32:08   作者:detayun  
在圖像處理任務(wù)中,調(diào)整圖片大小是一個常見需求,本文將介紹如何使用流行的Pillow庫(PIL)來輕松實現(xiàn)圖片縮放,感興趣的小伙伴可以了解下

在圖像處理任務(wù)中,調(diào)整圖片大小是一個常見需求。無論是為網(wǎng)頁優(yōu)化圖片、準備機器學(xué)習(xí)數(shù)據(jù)集,還是簡單調(diào)整照片尺寸,Python都提供了簡單高效的解決方案。本文將介紹如何使用流行的Pillow庫(PIL)來輕松實現(xiàn)圖片縮放。

為什么選擇Pillow庫?

Pillow是Python中最常用的圖像處理庫之一,它是PIL(Python Imaging Library)的一個友好分支。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: 目標尺寸,格式為(寬度, 高度)
    """
    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. 按比例縮放圖片

有時我們需要保持寬高比,只指定一個維度:

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
        
        # 計算縮放比例
        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)

高級縮放選項

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: 目標尺寸,格式為(寬度, 高度)
    """
    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} 時出錯: {e}")

# 使用示例
batch_resize_images("input_images", "output_images", (800, 600))

實際應(yīng)用案例

1. 為網(wǎng)頁準備縮略圖

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))
        
        # 計算居中位置
        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)整圖片大小同時保持EXIF信息

from PIL import Image, ExifTags

def resize_with_exif(input_path, output_path, size):
    """
    調(diào)整圖片大小并保留EXIF信息
    
    參數(shù):
        input_path: 輸入圖片路徑
        output_path: 輸出圖片路徑
        size: 目標尺寸,格式為(寬度, 高度)
    """
    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)化技巧

  1. 批量處理:使用Image.thumbnail()方法可以避免創(chuàng)建中間圖像對象
  2. 內(nèi)存管理:處理大量圖片時,及時關(guān)閉圖像對象或使用with語句
  3. 多線程處理:對于大量圖片,可以使用concurrent.futures實現(xiàn)并行處理
  4. 選擇合適格式:根據(jù)用途選擇輸出格式(JPEG適合照片,PNG適合圖形)

常見問題解答

Q: 縮放后的圖片質(zhì)量不佳怎么辦?

A: 使用高質(zhì)量的重采樣濾波器如Image.LANCZOS,并確保輸出格式支持高質(zhì)量(如JPEG質(zhì)量參數(shù)設(shè)為95)

Q: 如何保持圖片寬高比不變?

A: 使用thumbnail()方法或手動計算比例(如本文的resize_with_aspect_ratio函數(shù))

Q: Pillow支持哪些圖像格式?

A: 支持JPEG, PNG, BMP, GIF, TIFF等常見格式,完整列表見官方文檔

總結(jié)

Python的Pillow庫提供了強大而靈活的圖片縮放功能。從簡單的尺寸調(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)文章

最新評論

晴隆县| 南康市| 青河县| 凤城市| 株洲市| 虎林市| 高州市| 紫阳县| 五大连池市| 梁河县| 常德市| 晋宁县| 广汉市| 南和县| 贺兰县| 昌平区| 屏山县| 理塘县| 营口市| 府谷县| 金湖县| 伊吾县| 来安县| 合川市| 威宁| 来凤县| 永福县| 五原县| 巴塘县| 新源县| 宝兴县| 定边县| 噶尔县| 伊川县| 色达县| 久治县| 成武县| 东兰县| 莲花县| 宁远县| 平舆县|