PNGは汎用的な画像形式ですが、用途によってはJPEGやWEBPなど別の形式に変換したいことがあります。
今回は、PythonとPillowライブラリを使って、PNG画像を他形式に変換する方法をご紹介します。
単一ファイル変換版とディレクトリ一括変換版の両方を用意しました。
1. 環境構築
PNGの変換には、HEICのような追加ライブラリは不要です。
Pillow(PIL)だけで変換が可能です。
インストール
pip install pillow
- Pillow:Pythonの代表的な画像処理ライブラリ。JPEG、PNG、WEBPなど多くの形式に対応しています。
2. 単一ファイル変換スクリプト
ファイル名:convert_png_single.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
単一の PNG 画像を指定形式(JPEG, WEBP など)に変換するスクリプト
"""
from PIL import Image
import sys
import os
def convert_png(input_path, output_path, output_format="JPEG"):
"""
PNG画像を指定形式に変換する関数
:param input_path: 変換元のPNGファイル
:param output_path: 保存先ファイル
:param output_format: 出力形式(JPEG, WEBPなど Pillow対応形式)
"""
# PNG画像を開く
img = Image.open(input_path)
# JPEGなど透過非対応形式に変換する場合はRGBへ
if output_format.upper() == "JPEG":
img = img.convert("RGB")
# 保存
img.save(output_path, format=output_format)
print(f"変換完了: {output_path}")
if __name__ == "__main__":
if len(sys.argv) < 3:
print("使い方: python convert_png_single.py 入力.png 出力.jpg [形式]")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
fmt = sys.argv[3] if len(sys.argv) >= 4 else "JPEG"
if not os.path.exists(input_file):
print(f"ファイルが存在しません: {input_file}")
sys.exit(1)
convert_png(input_file, output_file, fmt)
実行例
python convert_png_single.py sample.png sample.jpg
形式を指定する場合(例:WEBP)
python convert_png_single.py sample.png sample.webp WEBP
3. ディレクトリ内一括変換スクリプト
ファイル名:convert_png_batch.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ディレクトリ内の PNG 画像を指定形式(JPEG, WEBP など)に一括変換するスクリプト
"""
from PIL import Image
import os
import glob
import sys
def convert_png(input_path, output_path, output_format="JPEG"):
"""
PNG画像を指定形式に変換する関数
"""
img = Image.open(input_path)
if output_format.upper() == "JPEG":
img = img.convert("RGB")
img.save(output_path, format=output_format)
print(f"変換完了: {output_path}")
if __name__ == "__main__":
if len(sys.argv) < 3:
print("使い方: python convert_png_batch.py 入力ディレクトリ 出力ディレクトリ [形式]")
sys.exit(1)
input_dir = sys.argv[1]
output_dir = sys.argv[2]
fmt = sys.argv[3] if len(sys.argv) >= 4 else "JPEG"
if not os.path.isdir(input_dir):
print(f"ディレクトリが存在しません: {input_dir}")
sys.exit(1)
os.makedirs(output_dir, exist_ok=True)
for png_file in glob.glob(os.path.join(input_dir, "*.png")):
base = os.path.splitext(os.path.basename(png_file))[0]
output_path = os.path.join(output_dir, f"{base}.{fmt.lower()}")
convert_png(png_file, output_path, fmt)
実行例
python convert_png_batch.py ./png_images ./converted_images
形式を指定する場合(例:WEBP)
python convert_png_batch.py ./png_images ./converted_images WEBP
4. オプションと注意点
- 入力ファイル/ディレクトリ:変換元のPNG画像を指定します。
- 出力ファイル/ディレクトリ:変換後の画像を保存する場所を指定します。
- [形式]:省略時はJPEG。
WEBP
,BMP
,GIF
など Pillow が対応する形式なら利用可能です。 - JPEG形式は透過情報が失われるため、透過が必要な場合はPNGやWEBPを選択してください。
5. まとめ
このスクリプトを使えば、PNG画像を簡単にJPEGやWEBPなどに変換できます。
単一ファイル変換はちょっとした用途に、一括変換は大量の画像変換に便利です。
また、Pillowだけで動作するため環境構築が非常にシンプルなのも利点です。
コメント