人妻夜夜爽天天爽三区丁香花-人妻夜夜爽天天爽三-人妻夜夜爽天天爽欧美色院-人妻夜夜爽天天爽免费视频-人妻夜夜爽天天爽-人妻夜夜爽天天

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

python命令行工具 圖片png轉webp

freeflydom
2025年2月2日 14:53 本文熱度 113

前言

網頁上使用webp格式的圖片更加省網絡流量和存儲空間,但本地圖片一般是png格式的,所以考慮用python的pillow庫將png格式的圖片轉換為webp格式。

需求:

  • 可以在系統任意地方調用。這需要編譯成二進制程序或寫成腳本放到PATH環境變量下
  • 支持指定圖片文件輸入目錄。默認為當前目錄。
  • 支持指定圖片文件輸出目錄。默認為輸入文件的同級目錄。
  • 支持指定圖片壓縮質量。默認為80。需要校驗傳參。
  • 支持并發同時壓縮多個圖片文件。默認為串行。傳參的并發數最大為CPU核心數。

代碼

from PIL import Image
import argparse
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
import os
from time import time
def parse_args():
    """解析命令行參數"""
    parser = argparse.ArgumentParser(description="Convert PNG to WEBP", 
        usage="""
        # 直接執行, 默認轉換當前目錄下的所有png文件到同級目錄
        python main.py
        # 將轉換后的webp文件保存到output目錄下
        python main.py -o output
        # 轉換單個png文件, 單獨轉換時不支持指定輸出目錄
        python main.py -f 1.png
        # 同時轉換, -t 指定最大并發數, 默認為1, 最大不得超過CPU核心數
        python main.py -t 2
        # 指定圖片壓縮質量, 默認為80, 取值區間為[0, 100], 值越高, 質量越好, 生成圖片體積越大
        python main.py -q 75
        """)
    parser.add_argument(
        "-i", type=str, default=os.getcwd(), help="Path to the input PNG image"
    )
    parser.add_argument(
        "-o", type=str, default=os.getcwd(), help="Path to the output WEBP image"
    )
    parser.add_argument("-f", type=str, default="", help="specific file name")
    parser.add_argument("-t", type=int, default=1, help="Number of threads to use")
    parser.add_argument(
        "-q", type=int, default=80, help="Quality of the output WEBP image"
    )
    return parser.parse_args()
def convert_png_to_webp(input_path: Path, output_path: Path, quality=80) -> None:
    """
    轉換PNG為WEBP
    Args:
        input_path (Path): 輸入文件路徑
        output_path (Path): 輸出文件路徑, 可以是一個目錄, 也可以是一個webp文件的路徑
        quality (int, optional): 圖片壓縮質量. 默認為 80.
    """
    # 如果quality不在0到100之間, 則設置為80
    if quality > 100 or quality < 0:
        print("quality must be between 0 and 100, now set to 80")
    real_q = quality if quality <= 100 and quality > 0 else 80
    # 如果輸入文件不存在, 則打印錯誤信息并返回
    if not input_path.exists():
        print(f"input file {input_path} not found")
        return
    # 如果指定了輸出目錄, 則嘗試創建輸出目錄
    if not output_path.exists() and output_path.suffix.lower() != ".webp":
        try:
            output_path.mkdir(parents=True)
        except Exception as e:
            print(e)
            print("Failed to create output directory")
            return
    # 如果指定了輸出目錄, 則修改輸出文件名為為輸入文件名, 并修改擴展名為.webp
    if output_path.suffix.lower() != ".webp":
        output_path = output_path / input_path.with_suffix(".webp").name
    start = time()
    try:
        with Image.open(input_path) as img:
            print(
                f"Converting {input_path}, quality={real_q}, size: {input_path.stat().st_size / 1024:.2f}KB"
            )
            img.save(output_path, "WEBP", quality=real_q)
            print(
                f"Convert png2webp successfully, output file: {output_path.name}, size: {int(output_path.stat().st_size) / 1024:.2f}KB, elapsed time: {time() - start:.2f}s"
            )
    except Exception as e:
        print(f"Convert png2webp failed: {e}")
def multi_thread_convert(max_workers: int, input_path, output_path, quality) -> None:
    """并發轉換png為webp"""
    print(f"convert png to webp with multi threads, max_workers: {max_workers}")
    p = Path(input_path)
    op = Path(output_path) if output_path != os.getcwd() else None
    max_workers = max_workers if max_workers < os.cpu_count() else os.cpu_count()
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        for f in p.glob("**/*.png"):
            executor.submit(
                convert_png_to_webp, f, op or f.with_suffix(".webp"), quality
            )
def main():
    start = time()
    args = parse_args()
    if not args.f:
        if args.t > 1:
            multi_thread_convert(args.t, args.i, args.o, args.q)
        else:
            p = Path(args.i)
            op = Path(args.o) if args.o != os.getcwd() else None
            for f in p.glob("**/*.png"):
                convert_png_to_webp(f, op or f.with_suffix(".webp"), args.q)
    else:
        p = Path(args.f)
        convert_png_to_webp(p, p.with_suffix(".webp"), args.q)
    print(f"Finished! Total elapsed time: {time() - start:.2f}s")
if __name__ == "__main__":
    main()

編譯

因為是在python虛擬環境中安裝的pillow,如果要在其它位置調用這個腳本,個人想了兩種方式:

  1. 另外編寫一個shell腳本,如果是windows,則編寫powershell腳本,在這個腳本內編寫調用邏輯,并把這個腳本放到PATH環境變量的路徑下。
  2. 編譯成二進制文件,將編譯好的二進制文件放到PATH環境變量下。這比較方便發送給別人,這樣別人就不需要在電腦上安裝python環境。

這里用pyinstaller將程序編譯成二進制文件,盡量在python虛擬環境下編譯,以減小二進制文件的體積

  1. 創建虛擬環境
python -m venv png2webp
  1. 激活虛擬環境
# linux
cd png2webp
source ./bin/activate
# windows powershell
cd png2webp
.\Scripts\activate
  1. 安裝依賴
python -m pip install pillow pyinstaller
  1. 編譯。注意修改實際的python文件路徑。
pyinstaller -F --clean .\main.py
  1. 生成的二進制文件在當前目錄下的dist目錄,將其放置到PATH環境變量下,如有需要可重命名。
  2. 測試在其他目錄下調用
png2webp --help

使用

# 直接執行, 默認轉換當前目錄下的所有png文件到同級目錄
png2webp
# 將轉換后的webp文件保存到output目錄下
png2webp -o output
# 轉換單個png文件, 單獨轉換時不支持指定輸出目錄
png2webp -f 1.png
# 同時轉換, -t 指定最大并發數, 默認為1, 最大不得超過CPU核心數
png2webp -t 2
# 指定圖片壓縮質量, 默認為80, 取值區間為[0, 100], 值越高, 質量越好, 生成圖片體積越大
png2webp -q 75

該文章在 2025/2/5 9:34:56 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

主站蜘蛛池模板: 日本免费精品视频丁香婷婷 | 国产图片一区 | 国产欧美日产中文一区 | 波多野吉不卡中文av | 国产精品卡1卡2卡3 国产精品卡1卡2卡3网站 | 五月色丁香婷婷网蜜臀AV | 国产中文在线亚 | 成熟妇女性成熟满足视频 | 99精品久久久久中文字幕 | 国产成人av区一区 | 男女高潮又爽又黄又无遮挡 | 亚洲AV国产国产久青草 | 麻豆国产主播精 | 欧美一区2区三 | 国产欧美一区二区三区不卡 | 日韩视频高清免费看 | 2024亚洲国产精品无码 | 欧美变态另类z0z0禽交 | av片在线观看不卡 | 欧美日韩整片中文字幕 | 精品人妻一区二区三区在线潮喷 | 亚洲国产日韩在线 | 欧美日韩一区蜜臀在 | 久久综合精品国产一区二区三区无码 | 欧美日韩一区二区成人 | 夜鲁夜鲁夜鲁视频在线观看 | 中文字幕人妻熟女在线 | 中文字幕αⅴ无码免费 | 91在线精品国产丝袜超清 | japanese熟女熟妇多毛毛 | 少妇人妻偷人精品无码av | 看看少妇的阳道毛偷拍女浴室 | 六月丁香婷婷综合 | 激情网址大全 | 中文字幕亚洲情99在线 | 亚洲毛片无码专区亚洲乱 | 中文在线日韩亚洲欧美 | 老司机午夜性生免费福利韩国福利一区二区美女视频 | 日韩成人无码v清免费 | 国产亚洲AV片在线观看16女人 | 国产精品无码无卡a级毛片 国产精品无码无卡毛片不卡视 |