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

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

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

在圖像處理任務(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)化技巧

  1. 批量處理:使用Image.thumbnail()方法可以避免創(chuàng)建中間圖像對象
  2. 內(nèi)存管理:處理大量圖片時(shí),及時(shí)關(guān)閉圖像對象或使用with語句
  3. 多線程處理:對于大量圖片,可以使用concurrent.futures實(shí)現(xiàn)并行處理
  4. 選擇合適格式:根據(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)文章

最新評論

灯塔市| 邵阳市| 鹿邑县| 台北市| 南和县| 萝北县| 齐河县| 泰和县| 东至县| 铁力市| 临猗县| 河曲县| 彰化市| 岚皋县| 林周县| 南木林县| 原平市| 玛纳斯县| 武隆县| 浮梁县| 陵川县| 都安| 建水县| 阳山县| 建阳市| 巍山| 沾化县| 克什克腾旗| 成都市| 阿巴嘎旗| 平安县| 江源县| 百色市| 栾城县| 北碚区| 巴彦县| 翁源县| 商洛市| 饶河县| 莒南县| 武隆县|