import os
import sys
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image
def select_folder(title):
root = tk.Tk()
root.withdraw()
folder_path = filedialog.askdirectory(title=title)
root.destroy()
return folder_path
def ask_yes_no(title, message):
root = tk.Tk()
root.withdraw()
result = messagebox.askyesno(title, message)
root.destroy()
return result
def resize_images(input_dir, output_dir, new_width):
valid_extensions = (".jpg", ".jpeg", ".png", ".bmp", ".webp")
if not os.path.exists(output_dir):
os.makedirs(output_dir)
count = 0
for file_name in os.listdir(input_dir):
# --- 追加: ドットで始まる隠しファイル(._ など)を無視する ---
if file_name.startswith('.'):
continue
if file_name.lower().endswith(valid_extensions):
input_path = os.path.join(input_dir, file_name)
if input_dir == output_dir:
name, ext = os.path.splitext(file_name)
output_name = f"{name}-s{ext}"
else:
output_name = file_name
output_path = os.path.join(output_dir, output_name)
try:
with Image.open(input_path) as img:
width, height = img.size
new_height = int(height * (new_width / width))
resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
resized_img.save(output_path)
print(f"完了: {output_name}")
count += 1
except Exception as e:
print(f"エラー: {file_name} -> {e}")
print(f"\n合計 {count} 枚の画像を '{output_dir}' に保存しました。")
def main():
target_dir = None
output_dir = None
target_width = None
# --- 1. 引数の柔軟な解析 ---
args = sys.argv[1:]
# 引数の中から「数値」を探して幅に設定、それ以外をパスとしてリスト化
paths = []
for arg in args:
if arg.isdigit():
target_width = int(arg)
else:
paths.append(arg)
# パスの割り当て
if len(paths) >= 1:
target_dir = paths[0]
if len(paths) >= 2:
output_dir = paths[1]
# --- 2. 入力フォルダの確定 ---
if not target_dir:
target_dir = select_folder("リサイズしたい画像があるフォルダを選択")
if not target_dir or not os.path.isdir(target_dir):
print("エラー: 入力フォルダが見つかりません。")
return
# --- 3. 横幅の確定 ---
if target_width is None:
while True:
val = input("リサイズ後の横幅(px)を数値で入力してください: ")
if val.isdigit():
target_width = int(val)
break
print("エラー: 半角数字のみを入力してください。")
# --- 4. 保存先フォルダの確定 ---
if not output_dir:
if ask_yes_no("保存先の確認", "保存先フォルダを別に指定しますか?\n(いいえを選ぶと同じフォルダに -s 付きで保存します)"):
output_dir = select_folder("保存先のフォルダを選択")
# まだ決まっていない、またはキャンセルされた場合は元のフォルダへ
if not output_dir:
output_dir = target_dir
# 実行
resize_images(target_dir, output_dir, target_width)
if __name__ == "__main__":
main()
|