2025-11-22 2025-11-22

概要

python で png画像から ico ファイルを作成する。

準備

pip install pillow

ソース

from PIL import Image
from pathlib import Path
import argparse
import sys


def main():
    parser = argparse.ArgumentParser(description="PNG ファイルを複数のサイズの ICO ファイルに変換します")
    parser.add_argument("png_path", help="PNGファイルのPATH")
    args = parser.parse_args()

    if not args.png_path:
        print("Error: 引数に画像ファイルのPATHを指定して下さい")
        sys.exit(1)

    png_path = Path(args.png_path)
    if not png_path.exists():
        print(f"Error: 画像ファイルが見つかりません: {png_path}")
        sys.exit(1)

    ico_path = png_path.with_suffix(".ico")

    img = Image.open(png_path).convert("RGBA")

    # 正方形でない場合は中央にリサイズする
    if img.width != img.height:
        size = min(img.width, img.height)
        img = img.crop((
            (img.width - size) // 2,
            (img.height - size) // 2,
            (img.width + size) // 2,
            (img.height + size) // 2,
        ))

    icon_sizes = [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
    img.save(ico_path, sizes=icon_sizes)


if __name__ == '__main__':
    main()

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2025-12-01 (月) 08:23:12 (4d)