python
import flet as ft
from PIL import Image, ImageDraw # Pillowライブラリが必要です: pip install Pillow
import io # 画像バイトデータを扱うために使用
def cropping_container(image_path: str, container_width: int = 400, container_height: int = 400):
"""
画像を選択し、クロッピング領域を指定できるFletコンポーネントを作成します。
Args:
image_path: 画像ファイルのパス。
container_width: 画像を表示するコンテナの幅。
container_height: 画像を表示するコンテナの高さ。
Returns:
A tuple containing:
- control: メインのFletコントロール (GestureDetector)。ページに追加します。
- image_ref: 内蔵の ft.Image コントロールを参照する ft.Ref オブジェクト。
- original_dims: 元画像の (幅, 高さ) タプル。
- status_ref: ft.Ref オブジェクト。呼び出し元はここに ft.Text コントロールを
割り当て、ステータスメッセージ(座標、エラーなど)を表示できます。
- coords_ref: ft.Ref オブジェクト。ユーザーが選択を完了した後、
[x1, y1, x2, y2] の形式(元の画像に対する座標)の結果リスト
が格納されます。呼び出し元はこの Ref の .current からデータ
を取得できます。
"""
# --- 内部状態変数 ---
# nonlocal を使用すると、ネストされた関数からこれらの変数を変更できます。
_start_x = 0.0
_start_y = 0.0
_is_drawing = False
_img_layout_width = 0.0 # Image コントロールの実際のレンダリング幅
_img_layout_height = 0.0 # Image コントロールの実際のレンダリング高さ
_original_width = 0
_original_height = 0
_coords_result = [-1, -1, -1, -1] # 結果を格納 [x1, y1, x2, y2]
# --- Flet Refオブジェクト ---
_rect_ref = ft.Ref[ft.Container]() # ドラッグ描画矩形用 Ref
_image_ref = ft.Ref[ft.Image]() # 画像自体用 Ref
_status_ref = ft.Ref() # 呼び出し元のステータス表示用 Text コントロール用 Ref
_coords_data_ref = ft.Ref() # 実際の座標リストデータを保持する Ref
# --- PILを使用して画像メタデータを読み込む ---
try:
img = Image.open(image_path)
_original_width, _original_height = img.size
if _original_width <= 0 or _original_height <= 0:
raise ValueError("画像寸法は正の値である必要があります。")
except FileNotFoundError:
error_msg = f"エラー: 画像ファイルが見つかりません '{image_path}'"
print(error_msg)
err_control = ft.Text(error_msg, color=ft.colors.RED)
return err_control, ft.Ref(), (0, 0), ft.Ref(), ft.Ref() # エラー時はプレースホルダを返す
except ValueError as ve:
error_msg = f"エラー: 画像 '{image_path}' の寸法が無効です。 {ve}"
print(error_msg)
err_control = ft.Text(error_msg, color=ft.colors.RED)
return err_control, ft.Ref(), (0, 0), ft.Ref(), ft.Ref()
except Exception as e:
error_msg = f"エラー: 画像 '{image_path}' の読み込み中にエラーが発生しました: {e}"
print(error_msg)
err_control = ft.Text(error_msg, color=ft.colors.RED)
return err_control, ft.Ref(), (0, 0), ft.Ref(), ft.Ref()
# --- イベントハンドラ ---
def _handle_layout(e: ft.LayoutEvent):
"""画像コントロールの実際のレンダリングサイズを取得するコールバック。"""
nonlocal _img_layout_width, _img_layout_height
_img_layout_width = _image_ref.current.width
_img_layout_height = _image_ref.current.height
def _handle_pan_start(e: ft.DragStartEvent):
"""ユーザーがドラッグを開始したときに呼び出されます。"""
nonlocal _start_x, _start_y, _is_drawing
_start_x = e.local_x
_start_y = e.local_y
_is_drawing = True
# 描画矩形をリセットして表示
_rect_ref.current.left = _start_x
_rect_ref.current.top = _start_y
_rect_ref.current.width = 0
_rect_ref.current.height = 0
_rect_ref.current.visible = True
_coords_result[:] = [-1, -1, -1, -1] # 内部結果をリセット
# ステータステキストが割り当てられていれば更新
if _status_ref.current and isinstance(_status_ref.current, ft.Text):
_status_ref.current.value = "Cropping..."
e.control.page.update()
def _handle_pan_update(e: ft.DragUpdateEvent):
"""ユーザーがドラッグしている間、継続的に呼び出されます。"""
if not _is_drawing:
return
current_x = e.local_x
current_y = e.local_y
# 矩形の座標と寸法を計算
x1 = min(_start_x, current_x)
y1 = min(_start_y, current_y)
width = abs(_start_x - current_x)
height = abs(_start_y - current_y)
# 画像のレイアウト境界内に描画が収まるようにクリッピング
img_w = _img_layout_width if _img_layout_width > 0 else 1 # 安全のためゼロ除算回避
img_h = _img_layout_height if _img_layout_height > 0 else 1
clipped_x1 = max(0.0, x1)
clipped_y1 = max(0.0, y1)
# クリッピングされた開始点から境界を超えないように幅/高さを計算
clipped_width = max(0.0, min(width, img_w - clipped_x1))
clipped_height = max(0.0, min(height, img_h - clipped_y1))
# ビジュアル上の矩形を更新
_rect_ref.current.left = clipped_x1
_rect_ref.current.top = clipped_y1
_rect_ref.current.width = clipped_width
_rect_ref.current.height = clipped_height
e.control.page.update()
def _handle_pan_end(e: ft.DragEndEvent):
"""ユーザーがマウスボタンを離したときに呼び出されます。"""
nonlocal _is_drawing, _coords_result
if not _is_drawing:
return
_is_drawing = False
# スタック/画像レイアウト領域に対する最終的な矩形座標を取得
final_rect_x1 = _rect_ref.current.left
final_rect_y1 = _rect_ref.current.top
final_rect_x2 = final_rect_x1 + _rect_ref.current.width
final_rect_y2 = final_rect_y1 + _rect_ref.current.height
# クロップ領域が有効か検証(最小サイズ)
if _rect_ref.current.width <= 1 or _rect_ref.current.height <= 1:
_rect_ref.current.visible = False # 矩形を非表示
_coords_result[:] = [-1, -1, -1, -1] # 内部データをリセット
if _status_ref.current and isinstance(_status_ref.current, ft.Text):
_status_ref.current.value = "無効なクロップ領域(小さすぎます)。"
e.control.page.update()
return
# --- 座標変換 ---
# ImageFit.CONTAIN の動作により、アスペクト比が異なる場合に
# レターボックス/ピラーボックスが発生するため、スケーリング係数とオフセットを計算。
if _img_layout_width <= 0 or _img_layout_height <= 0:
error_msg = "エラー: 有効な画像レイアウト寸法がないため、座標を変換できません。"
print(error_msg)
_coords_result[:] = [-1, -1, -1, -1]
if _status_ref.current and isinstance(_status_ref.current, ft.Text):
_status_ref.current.value = error_msg
_rect_ref.current.visible = False
e.control.page.update()
return
# 有効なレンダリング寸法とオフセットを計算
orig_ratio = _original_width / _original_height
render_ratio = _img_layout_width / _img_layout_height
scale_x, scale_y, x_offset, y_offset, render_w, render_h = 1.0, 1.0, 0.0, 0.0, _img_layout_width, _img_layout_height
if orig_ratio > render_ratio: # 元画像がコンテナよりも縦横比が横長
render_w = _img_layout_width # 画像はコンテナの幅に合わせる
render_h = _img_layout_width / orig_ratio # 高さを比例計算
y_offset = (_img_layout_height - render_h) / 2.0 # 垂直方向に中央揃え
else: # 元画像がコンテナよりも縦横比が縦長、または同じ場合
render_h = _img_layout_height # 画像はコンテナの高さに合わせる
render_w = _img_layout_height * orig_ratio # 幅を比例計算
x_offset = (_img_layout_width - render_w) / 2.0 # 水平方向に中央揃え
scale_x = _original_width / render_w
scale_y = _original_height / render_h
# 最終的な矩形座標(レイアウト領域基準)を
# 元画像の座標系にマッピングする。
final_orig_x1 = max(0, int((final_rect_x1 - x_offset) * scale_x))
final_orig_y1 = max(0, int((final_rect_y1 - y_offset) * scale_y))
final_orig_x2 = min(_original_width, int((final_rect_x2 - x_offset) * scale_x))
final_orig_y2 = min(_original_height, int((final_rect_y2 - y_offset) * scale_y))
# 変換とクリッピング後の最終検証
if final_orig_x2 > final_orig_x1 and final_orig_y2 > final_orig_y1:
_coords_result[:] = [final_orig_x1, final_orig_y1, final_orig_x2, final_orig_y2]
if _status_ref.current and isinstance(_status_ref.current, ft.Text):
_status_ref.current.value = f"選択領域: [{final_orig_x1}, {final_orig_y1}, {final_orig_x2}, {final_orig_y2}]"
else:
_coords_result[:] = [-1, -1, -1, -1] # 無効としてマーク
if _status_ref.current and isinstance(_status_ref.current, ft.Text):
_status_ref.current.value = "変換後に無効なクロップ領域。"
# 矩形を非表示にし、UIを更新
_rect_ref.current.visible = False
e.control.page.update()
# --- Flet コントロール定義 ---
image_control = ft.Image(
ref=_image_ref,
src=image_path,
width=container_width,
height=container_height,
fit=ft.ImageFit.CONTAIN, # コンテナに合わせてスケーリング
on_layout=_handle_layout, # レンダリングサイズ取得用コールバック
# Flet内で画像読み込みに失敗した場合のエラー表示
error_content=ft.Container(height=container_height, width=container_width, content=ft.Text(f"画像読み込みエラー"), bgcolor=ft.colors.BLACK12)
)
drawing_rect = ft.Container(
ref=_rect_ref,
width=0, height=0,
bgcolor=ft.colors.RED_ACCENT_700,
opacity=0.3,
border_radius=3,
# Stack内のコントロールは top/left で絶対配置
top=0, left=0,
visible=False # 初期状態は非表示
)
# 画像と描画矩形を重ねるためのStack
stack = ft.Stack(
width=container_width,
height=container_height,
controls=[
image_control,
drawing_rect,
]
)
# ドラッグイベントをキャプチャするためのGestureDetectorでStackをラップ
gesture_detector = ft.GestureDetector(
content=stack,
on_pan_start=lambda e: _handle_pan_start(e),
on_pan_update=lambda e: _handle_pan_update(e),
on_pan_end=lambda e: _handle_pan_end(e),
drag_interval=10, # ドラッグイベントのトリガー間隔(ミリ秒)
)
# 実際の座標リストをデータRefに割り当てる
_coords_data_ref.current = _coords_result
# メインコントロール、アクセス用のRef、元画像寸法、ステータス/データ用Refを返す
return gesture_detector, _image_ref, (_original_width, _original_height), _status_ref, _coords_data_ref
# --- 使用例 ---
def main(page: ft.Page):
"""cropping_container関数を実演するサンプルFletアプリ。"""
page.title = "Flet 画像クロッピングコンポーネント"
page.vertical_alignment = ft.MainAxisAlignment.START
page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
page.window_width = 500
page.window_height = 850
# 画像パスとコンテナサイズを定義
# テスト用にダミー画像(例:横長画像)を作成(存在しない場合)
image_file = "test_landscape.png"
try:
# 画像が存在するか確認し、なければ作成
with open(image_file, "rb") as f:
pass # File exists
except FileNotFoundError:
print(f"ダミー画像を作成中: {image_file}")
try:
img_pil = Image.new('RGB', (800, 400), color='cadetblue') # 横長画像
draw = ImageDraw.Draw(img_pil)
draw.text((10, 10), "800x400 Landscape", fill=(0, 0, 0))
img_pil.save(image_file)
except Exception as e:
print(f"ダミー画像の作成に失敗しました: {e}")
# cropping_container関数を使用
crop_component, img_ref, original_dims, status_ref, coords_ref = cropping_container(
image_path=image_file,
container_width=400,
container_height=300
)
# ステータスメッセージ用の Text コントロールを作成し、status_ref を使用してリンク
status_text_control = ft.Text("画像上でドラッグしてクロップ領域を選択してください。", size=14)
status_ref.current = status_text_control
def get_and_process_coords(e):
"""座標を取得して処理するコールバック関数。"""
selected_coords = coords_ref.current # リスト [x1, y1, x2, y2] を取得
print(f"取得した座標: {selected_coords}")
# 必要に応じてステータスメッセージを更新
if status_text_control:
if selected_coords and selected_coords[0] != -1:
status_text_control.value = f"最終座標: [{selected_coords[0]}, {selected_coords[1]}, {selected_coords[2]}, {selected_coords[3]}]"
else:
status_text_control.value = "有効なクロップが選択されていません。"
# 例: 座標をPILで使用して元の画像をクロップする
if selected_coords and selected_coords[0] != -1:
try:
original_img_pil = Image.open(image_file)
# PILの crop メソッドはボックスタプル (left, upper, right, lower) を使用
cropped_img_pil = original_img_pil.crop(selected_coords)
print(f"PILでクロップされた画像のサイズ: {cropped_img_pil.size}")
# PIL画像をFlet互換フォーマット(例:バイト配列 PNG)に変換
img_byte_arr = io.BytesIO()
cropped_img_pil.save(img_byte_arr, format='PNG')
img_bytes = img_byte_arr.getvalue()
# クロップされた画像を表示(オプション)
result_image_control = ft.Image(
src_base64=ft.bytes_to_base64(img_bytes),
width=200,
height=150, # アスペクト比を維持するため高さを調整
fit=ft.ImageFit.CONTAIN,
border_radius=ft.border_radius.all(5)
)
# 結果の画像コントロールをページに動的に追加
page.add(ft.Text("クロップ結果:"), result_image_control)
page.update()
except FileNotFoundError:
status_text_control.value = "エラー: クロップ処理中に元の画像ファイルが見つかりません。"
except Exception as e:
status_text_control.value = f"クロップ処理エラー: {e}"
print(f"クロップ処理エラー: {e}")
else:
if status_text_control:
status_text_control.value = "まず有効なクロップ領域を選択してください。"
page.update() # ステータス更新を表示させる
# ページ上にコントロールを配置
page.add(
ft.Column(
[
ft.Text("画像クロッピングツール", size=20, weight=ft.FontWeight.BOLD),
# クロッピングコンポーネントを追加
crop_component,
# ステータスメッセージを表示(リンクされたTextコントロールを使用)
status_text_control,
# 座標取得とプレビュー処理をトリガーするボタン
ft.ElevatedButton("クロップ座標を取得 & プレビュー", on_click=get_and_process_coords),
# 元画像の寸法を参照用に表示
ft.Text(f"元の画像寸法: {original_dims[0]}x{original_dims[1]}", size=12)
],
width=450, # 列の幅を制限して見栄えを良くする
horizontal_alignment=ft.CrossAxisAlignment.CENTER
)
)
# --- Flet アプリを実行 ---
if __name__ == "__main__":
ft.app(target=main)