""" image_tools.py 画像関連の変換処理 - heic-jpg : HEIC → JPEG - jpeg-pdf : JPEG/PNG 複数枚 → 1つの PDF - pdf-png : PDF の各ページ → PNG """ import os import subprocess from typing import List from PIL import Image try: from pillow_heif import register_heif_opener register_heif_opener() PILLOW_HEIF_AVAILABLE = True except Exception: PILLOW_HEIF_AVAILABLE = False from pdf2image import convert_from_path from tools.base_tool import tasks # ---------- HEIC → JPG ---------- def convert_heic_to_jpg(task_id: str, filenames: List[str], input_path: str, output_path: str): """HEIC ファイルを JPEG に変換する(ImageMagick → pillow-heif の順でフォールバック)""" for i, fname in enumerate(filenames): in_f = os.path.join(input_path, fname) out_f = os.path.join(output_path, f"{os.path.splitext(fname)[0]}.jpg") tasks[task_id]["last_log"] = f"処理中: {fname}" tasks[task_id]["progress"] = int(20 + (i / len(filenames)) * 60) converted = False # まず ImageMagick で試みる(最も確実) try: result = subprocess.run( ["convert", in_f, "-quality", "95", out_f], capture_output=True, timeout=60 ) if result.returncode == 0 and os.path.exists(out_f): converted = True except Exception: pass # フォールバック: pillow-heif if not converted and PILLOW_HEIF_AVAILABLE: img = Image.open(in_f) img.convert("RGB").save(out_f, "JPEG", quality=95) converted = True if not converted: raise Exception( f"HEIC変換に失敗しました: {fname}。" "ImageMagickおよびpillow-heifが利用できません。" ) # ---------- JPEG/PNG → PDF ---------- def convert_jpeg_to_pdf(task_id: str, filenames: List[str], input_path: str, output_path: str): """複数の画像ファイルを1つの PDF に結合する""" imgs = [] for fname in filenames: in_f = os.path.join(input_path, fname) imgs.append(Image.open(in_f).convert("RGB")) if not imgs: raise Exception("変換対象の画像がありません") out_pdf = os.path.join(output_path, "output.pdf") imgs[0].save(out_pdf, "PDF", save_all=True, append_images=imgs[1:]) tasks[task_id]["progress"] = 80 # ---------- PDF → PNG ---------- def convert_pdf_to_png(task_id: str, filenames: List[str], input_path: str, output_path: str): """PDF の各ページを PNG 画像に変換する""" for i, fname in enumerate(filenames): in_f = os.path.join(input_path, fname) tasks[task_id]["last_log"] = f"処理中: {fname}" tasks[task_id]["progress"] = int(20 + (i / len(filenames)) * 60) images = convert_from_path(in_f) for j, image in enumerate(images): image.save( os.path.join(output_path, f"{os.path.splitext(fname)[0]}_{j}.png"), "PNG" )