LoginSignup
0
0

[メモ] batファイルからPythonファイルを呼び出す

Posted at

フォルダ内の画像サイズをチェックする方法

画像フォルダ内にbatファイルを配置し、
Cドライブ内のbatchフォルダに格納されている
Pythonファイルを実行して
画像サイズが適切かを調べる処理

@echo off
setlocal

REM 画像の横サイズを指定
set "WIDTH=3840"
REM 画像の縦サイズを指定
set "HEIGHT=2112"

REM カレントディレクトリを取得
set "CURRENT_DIR=%CD%"

REM Pythonスクリプトを実行
python "C:\batch\test.py" "%CURRENT_DIR%" "%WIDTH%x%HEIGHT%"

endlocal
echo Waiting for 5 seconds...
timeout /t 5 /nobreak >nul
exit

カレントディレクトリを、
指定パス内のPythohnファイルに渡す

import os
import sys
from PIL import Image

def main():
    # カレントディレクトリを取得
    current_dir = sys.argv[1]
    file_size = sys.argv[2] if len(sys.argv)>2 else ""
    print(f"Current directory: {current_dir}")
    print(f"Ideal Image Size: {file_size}")

    files = os.listdir(current_dir)
    print("----- file check -----")

    # 指定のフォルダ内の画像ファイルを処理
    for filename in files:
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            image_path = os.path.join(current_dir, filename)
            try:
                with Image.open(image_path) as img:
                    width, height = img.size
                    if file_size==f"{width}x{height}":
                        print(f"Image: {filename}, Size: {width}x{height}")
                    else:
                        print(f"\033[91mImage: {filename}, Size: {width}x{height}\033[0m")
            except Exception as e:
                print(f"\033[91mUNKNOWN ERROR : {filename}\033[0m")
    print("----- file check end -----")
    print()

if __name__ == "__main__":
    main()

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0