ChatGPT)Python)OTFフォント、TTFフォントをWOFF2フォントに変換するWindowsアプリ作成。

2025-09-30 · コンピュータ アート・美術 <AI>

フォントファイルは、拡張子がOTFかTTF。

そのままでもHTML、CSSで利用できるが、WOFF2の方がWeb用に最適化された形式で、軽量でブラウザ互換性が高い。

OTFフォント、TTFフォントをWOFF2フォントに変換するWindowsアプリをPythonで作成。ChatGPTで作成。

【Pythonプログラム】

OTFフォント、TTFフォントが入ったフォルダーを指定して、「変換」ボタンを押すと、同じフォルダー内にWOFF2ファイルが出来る。複数ファイルがあれば、一括処理する。

【Pythonライブラリインストール】

次のライブラリが必要なので、インストールする。

pip install fonttools brotli

【Pythonプログラムコード】

"""
ttf_otf_to_woff2.py
Windows用のシンプルなGUIアプリ(tkinter)
OTF / TTF を同じフォルダ内に WOFF2 ファイルを生成します。

依存:
  pip install fonttools brotli
  ※fonttools が woff2 を出力するために brotli が必要です。
  もしそれでも失敗する場合は、Google の woff2 コマンドラインツールをインストールして
  パスに置くとフォールバックで利用します(woff2_compress)。

使い方:
  - アプリ起動 -> フォルダ選択 -> フォルダ内の .ttf/.otf を一覧表示
  - 変換 ボタンを押すと、同じフォルダに同名の .woff2 を作成します

注意:
  - 元のファイルは上書きされません(別拡張子の出力)
  - サブフォルダは探索しません(必要ならコードを拡張してください)

"""

import os
import threading
import subprocess
import shutil
import traceback
from tkinter import Tk, StringVar, LEFT, END, BOTH, YES, N, S, E, W
from tkinter import ttk, filedialog, messagebox, scrolledtext

try:
    from fontTools.ttLib import TTFont
except Exception:
    TTFont = None


def convert_font_with_fonttools(src_path, dst_path):
    """fontTools を使って .woff2 に変換する。"""
    if TTFont is None:
        raise RuntimeError("fontTools が import できません。pip install fonttools brotli を実行してください。")
    # fontTools はOTF/TTFどちらも読み込める
    font = TTFont(src_path)
    font.flavor = 'woff2'
    # 既存のファイルを上書きするために一時ファイルで保存してから移すのも良いが
    # ここでは直接保存する
    font.save(dst_path)


def convert_font_with_woff2_binary(src_path, dst_path):
    """woff2_compress(Googleのツール)を使って変換するフォールバック。
    woff2_compress <input> -> <input>.woff2
    ここでは出力パスを指定するため一旦標準出力の挙動に依存せず一時ファイルを作る。
    """
    woff2_cmd = shutil.which('woff2_compress') or shutil.which('woff2')
    if not woff2_cmd:
        raise RuntimeError('woff2_compress 実行ファイルが見つかりません。')
    # woff2_compress は通常 input -> input.woff2 を出すので、同じフォルダで実行する
    work_dir = os.path.dirname(src_path)
    try:
        # 実行: woff2_compress "src_path"
        subprocess.check_call([woff2_cmd, src_path], cwd=work_dir)
        produced = src_path + '.woff2'
        if not os.path.exists(produced):
            # 一部のビルドでは拡張子なし等の可能性があるが稀
            raise RuntimeError('woff2_compress は出力ファイルを生成しませんでした')
        # 移動(上書き)
        if os.path.abspath(produced) != os.path.abspath(dst_path):
            if os.path.exists(dst_path):
                os.remove(dst_path)
            shutil.move(produced, dst_path)
    except subprocess.CalledProcessError as e:
        raise RuntimeError(f'woff2_compress の実行が失敗しました: {e}')


class ConverterApp:
    def __init__(self, root):
        self.root = root
        root.title('OTF/TTF → WOFF2 変換')
        root.geometry('700x420')

        self.folder_var = StringVar()

        top_frame = ttk.Frame(root, padding=8)
        top_frame.pack(fill='x')

        ttk.Label(top_frame, text='フォルダ:').pack(side=LEFT)
        self.folder_entry = ttk.Entry(top_frame, textvariable=self.folder_var)
        self.folder_entry.pack(side=LEFT, fill='x', expand=True, padx=6)
        ttk.Button(top_frame, text='参照', command=self.browse_folder).pack(side=LEFT)
        ttk.Button(top_frame, text='リフレッシュ', command=self.refresh_list).pack(side=LEFT, padx=4)

        mid_frame = ttk.Frame(root, padding=(8, 6))
        mid_frame.pack(fill='both', expand=True)

        # ファイル一覧
        self.file_list = ttk.Treeview(mid_frame, columns=('name','size'), show='headings')
        self.file_list.heading('name', text='ファイル名')
        self.file_list.heading('size', text='サイズ')
        self.file_list.column('name', width=420)
        self.file_list.column('size', width=120, anchor='e')
        self.file_list.pack(fill='both', expand=True, side='left')

        # ログ
        right_frame = ttk.Frame(mid_frame)
        right_frame.pack(fill='y', side='left', padx=8)
        ttk.Label(right_frame, text='ログ').pack()
        self.log = scrolledtext.ScrolledText(right_frame, width=40, height=15, state='disabled')
        self.log.pack(fill='both', expand=True)

        bottom_frame = ttk.Frame(root, padding=8)
        bottom_frame.pack(fill='x')
        self.progress = ttk.Progressbar(bottom_frame, mode='determinate')
        self.progress.pack(fill='x', side='left', expand=True)
        ttk.Button(bottom_frame, text='変換', command=self.start_conversion).pack(side='left', padx=8)

        # 初期状態
        self.current_files = []

    def log_message(self, msg):
        self.log.config(state='normal')
        self.log.insert(END, msg + '\n')
        self.log.see('end')
        self.log.config(state='disabled')

    def browse_folder(self):
        d = filedialog.askdirectory()
        if d:
            self.folder_var.set(d)
            self.refresh_list()

    def refresh_list(self):
        folder = self.folder_var.get().strip()
        for i in self.file_list.get_children():
            self.file_list.delete(i)
        self.current_files = []
        if not folder or not os.path.isdir(folder):
            return
        for name in sorted(os.listdir(folder)):
            lname = name.lower()
            if lname.endswith('.ttf') or lname.endswith('.otf'):
                full = os.path.join(folder, name)
                try:
                    size = os.path.getsize(full)
                except Exception:
                    size = 0
                self.file_list.insert('', 'end', values=(name, f'{size} bytes'))
                self.current_files.append(full)

    def start_conversion(self):
        if not self.current_files:
            messagebox.showinfo('情報', '変換する TTF/OTF ファイルが見つかりません。')
            return
        # Run conversion in background thread to keep UI responsive
        t = threading.Thread(target=self.convert_all)
        t.daemon = True
        t.start()

    def convert_all(self):
        total = len(self.current_files)
        self.progress['maximum'] = total
        self.progress['value'] = 0
        success = 0
        for idx, src in enumerate(self.current_files, start=1):
            try:
                base, _ = os.path.splitext(src)
                dst = base + '.woff2'
                self.log_message(f'[{idx}/{total}] {os.path.basename(src)} -> {os.path.basename(dst)}')
                # 既に出力ファイルがある場合はスキップまたは上書き(ここでは上書き)
                if os.path.exists(dst):
                    self.log_message('  既に存在するため上書きします。')
                    try:
                        os.remove(dst)
                    except Exception as e:
                        self.log_message(f'  既存ファイルの削除に失敗: {e}')
                # まず fonttools を試す
                try:
                    convert_font_with_fonttools(src, dst)
                    self.log_message('  変換成功 (fontTools)')
                    success += 1
                except Exception as e1:
                    self.log_message(f'  fontTools で失敗: {e1}')
                    # フォールバックで woff2_compress が使えるか試す
                    try:
                        convert_font_with_woff2_binary(src, dst)
                        self.log_message('  変換成功 (woff2_compress)')
                        success += 1
                    except Exception as e2:
                        self.log_message(f'  woff2_compress でも失敗: {e2}')
                        self.log_message('  ----- 変換失敗の詳細 -----')
                        tb = traceback.format_exc()
                        self.log_message(tb)
                finally:
                    self.progress['value'] = idx
            except Exception as e:
                self.log_message(f'予期しないエラー: {e}')
                tb = traceback.format_exc()
                self.log_message(tb)
        self.log_message(f'完了: 成功 {success} / {total}')
        messagebox.showinfo('完了', f'変換処理が終わりました。成功 {success} / {total}')
        # 更新して結果を反映
        self.refresh_list()


if __name__ == '__main__':
    root = Tk()
    app = ConverterApp(root)
    root.mainloop()

カリグラフィー・フォント(カッパープレート体)。Web(HTML、CSS)での利用。Windowsでの利用。カリグラフィー っぽい(?) カッパープレート体 の無料フォントを探したが、自分がイメージしているようなフォントはなかなか見つからない。 と…晴歩雨描 ·

晴歩雨描:記事一覧ok2nd.github.io

Claude)Python)シンプルなWindows用ランチャーアプリ作成。Pythonで作成したWindows用アプリが増えてきた。 これらを起動する ランチャーアプリ が欲しいと思って、作成した。 設定できる項目…晴歩雨描 ·

Claude)Python)PowerPointに複数写真(画像)を順番に並べて貼り付けるプログラム作成(改訂版)。以前に、PowerPointに複数写真を順番に並べて貼り付けるプログラムをPythonで作成した。 今回、このプログラムの改訂版。前回と同じ…晴歩雨描 ·

Claude)Python)写真のEXIF情報を表示するWindowsアプリ(ExifTool)を作成。Pythonで「 写真のEXIF情報を表示する 」Windowsアプリを作成。「Claude」で作成。 【機能概略】 JPEGファイルを画面…晴歩雨描 ·

Claude)Python)透過画像作成Windowsアプリ作成。Pythonで「透過画像作成」Windowsアプリ作成。画像の白に近い色を透過にする。元データはJPEGまたはPNG。白の範囲は指定できる。…晴歩雨描 ·

Claude)Python)「写真オブジェクト除去」Windowsアプリ作成。シミ消しにも使える。2日前、 JavaScript で「 写真スポッティング編集ツール 」を作成した。 今回、 Python で「 写真オブジェクト除去アプリ …晴歩雨描 ·

Claude)Python)ローカル)写真のシャープネス、コントラスト、明度、彩度を調整するWindowsアプリ作成。野鳥写真で、等倍高画質化をTopaz Labs、Aiarty Image Enhancerと比較。Pythonで「 写真のシャープネス、コントラスト、明度、彩度を調整する 」Windowsアプリを作成。「Claude」で作成。 【機能概略…晴歩雨描 ·

Claude&Gemini)Python)「写真のトーンカーブ一括補正」Windowsアプリ作成。先日、Pythonで「写真の明るさ&コントラスト一括補正」Windowsアプリを作成した。 今回、 トーンカーブを使って写真の明るさを補正す…晴歩雨描 ·

Claude&Gemini)Python)「写真のカラーバランス一括補正」Windowsアプリ作成。Pixel 9 Proの青被りを補正。スマホ「 Pixel 9 Pro 」を所有しているが、写真の青被りがきつい。特に人物の顔色が悪くなる。GIMP等でカラーバランスを調整するこ…晴歩雨描 ·

Claude)Python)「写真の明るさ&コントラスト一括補正」Windowsアプリ作成。ICCプロファイル維持。Pythonで「 写真の明るさ&コントラスト一括補正 」Windowsアプリ作成。 複数の画像を一括して補正できる。 AIツールClaude…晴歩雨描 ·

Claude)Python)「写真をEXIF機種毎のフォルダーに分類」Windowsアプリ作成。Pythonで「写真をEXIF機種毎のフォルダーに分類」Windowsアプリを作成。 生成AI「 Claude 」「 Gemini 」「 C…晴歩雨描 ·

Gemini)Python)「ファイル拡張子別フォルダー移動」Windowsアプリ作成。Pythonで「ファイル拡張子別フォルダー移動」Windowsアプリを作成。 生成AI「 Gemini 」「 Claude 」「 ChatG…晴歩雨描 ·