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

從入門到實戰(zhàn)詳解Python壓縮圖片的完整方法

 更新時間:2026年06月03日 08:28:03   作者:detayun  
這篇文章主要為大家詳細介紹了Python實現(xiàn)壓縮圖片的常見方法,主要是Python庫Pillow,OpenCV及tinify,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下

圖片太大,上傳慢、存儲貴、加載卡?用 Python 幾行代碼就能搞定。

為什么要壓縮圖片

  • 網(wǎng)站加速:圖片占網(wǎng)頁流量的 60%+,壓縮后加載速度提升明顯
  • 節(jié)省存儲:一張 10MB 的照片壓到 500KB,硬盤壓力小很多
  • 符合平臺限制:微信、微博、電商平臺都有圖片大小上限

方案一:Pillow(最推薦,簡單夠用)

Pillow 是 Python 最主流的圖像處理庫,壓縮圖片只需幾行代碼。

1. 按質量壓縮(有損)

from PIL import Image

def compress_image(input_path, output_path, quality=85):
    """
    quality: 1-100,越小文件越小,畫質越差
    推薦值:70-85 之間性價比最高
    """
    img = Image.open(input_path)
    
    # JPEG 不支持透明通道,需要轉換模式
    if img.mode in ('RGBA', 'P'):
        img = img.convert('RGB')
    
    img.save(output_path, 'JPEG', optimize=True, quality=quality)
    
    original_size = os.path.getsize(input_path) / 1024
    new_size = os.path.getsize(output_path) / 1024
    print(f"原大小: {original_size:.1f}KB → 壓縮后: {new_size:.1f}KB,節(jié)省 {100 - new_size/original_size*100:.1f}%")

compress_image("photo.jpg", "photo_compressed.jpg", quality=80)

2. 按尺寸壓縮(縮小分辨率)

def resize_image(input_path, output_path, max_width=1200):
    img = Image.open(input_path)
    
    w, h = img.size
    if w > max_width:
        ratio = max_width / w
        new_size = (max_width, int(h * ratio))
        img = img.resize(new_size, Image.LANCZOS)  # LANCZOS 是高質量縮放算法
    
    img.save(output_path, 'JPEG', optimize=True, quality=85)

3. 批量壓縮整個文件夾

import os
from PIL import Image

def batch_compress(input_dir, output_dir, quality=80):
    os.makedirs(output_dir, exist_ok=True)
    
    for filename in os.listdir(input_dir):
        if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)
            
            img = Image.open(input_path)
            if img.mode in ('RGBA', 'P'):
                img = img.convert('RGB')
            img.save(output_path, 'JPEG', optimize=True, quality=quality)
            print(f"? {filename}")

batch_compress("./photos", "./photos_compressed", quality=75)

方案二:OpenCV(適合需要更多控制的場景)

import cv2

def compress_with_cv2(input_path, output_path, quality=80):
    img = cv2.imread(input_path)
    # quality 參數(shù)范圍 0-100
    cv2.imwrite(output_path, img, [cv2.IMWRITE_JPEG_QUALITY, quality])

OpenCV 優(yōu)勢是可以順便做裁剪、旋轉、加水印等操作,再一起壓縮。

方案三:tinify(API 壓縮,效果最好)

如果追求極致壓縮比,可以用 tinify 的 API,它用的是有損+無損混合算法。

import tinify

tinify.key = "你的API_KEY"
source = tinify.from_file("photo.jpg")
source.to_file("photo_tiny.jpg")

免費額度每月 500 張,超出后付費,但壓縮效果確實比 Pillow 好 20%-40%。

幾個實用技巧

技巧說明
quality=85 是 sweet spot低于 70 肉眼可見模糊,高于 90 壓縮效果很弱
先縮尺寸再壓質量效果翻倍,比如先 resize 到 1200px 寬,再 quality=80
PNG 轉 JPEG如果不需要透明通道,PNG 轉 JPEG 體積能縮小 70%+
用 WebP 格式同等畫質下比 JPEG 小 30%,現(xiàn)代瀏覽器全支持
optimize=True 別忘加Pillow 的這個參數(shù)會額外做一次無損優(yōu)化,白撿的壓縮

到底選哪個?

需求推薦方案
快速搞定、批量處理Pillow
要同時做圖像處理(裁剪/旋轉)OpenCV
追求最小體積、不差錢tinify API
面向 Web 前端輸出轉為 WebP 格式

完整實戰(zhàn)腳本(直接復制就能用)

import os
from PIL import Image

def smart_compress(input_path, output_path, max_width=1920, quality=80):
    img = Image.open(input_path)
    
    # 1. 轉換模式
    if img.mode in ('RGBA', 'P'):
        img = img.convert('RGB')
    
    # 2. 縮小尺寸
    w, h = img.size
    if w > max_width:
        ratio = max_width / w
        img = img.resize((max_width, int(h * ratio)), Image.LANCZOS)
    
    # 3. 壓縮保存
    img.save(output_path, 'JPEG', optimize=True, quality=quality)
    
    original = os.path.getsize(input_path) / 1024
    compressed = os.path.getsize(output_path) / 1024
    print(f"{os.path.basename(input_path)}: {original:.0f}KB → {compressed:.0f}KB")

# 使用
smart_compress("large_photo.jpg", "small_photo.jpg")

圖片壓縮的核心就一句話:先縮尺寸,再調質量,能轉格式就轉格式。掌握這三步,90% 的場景都夠用了。

到此這篇關于從入門到實戰(zhàn)詳解Python壓縮圖片的完整方法的文章就介紹到這了,更多相關Python壓縮圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

钟祥市| 临汾市| 义马市| 临夏县| 金门县| 谢通门县| 石台县| 基隆市| 兴义市| 绥棱县| 临泉县| 浪卡子县| 日照市| 定州市| 饶河县| 乌拉特前旗| 承德县| 麻城市| 玛纳斯县| 余江县| 商河县| 仙游县| 霍林郭勒市| 阳信县| 华坪县| 孝感市| 宿迁市| 宜君县| 福清市| 建水县| 蒙阴县| 民勤县| 开鲁县| 镇康县| 南投市| 长沙市| 济宁市| 塔河县| 潢川县| 措美县| 买车|