画像をリサイズするPowerShellプログラム

f:id:piyo_yeah:20190211212912p:plain

ソースコード

# アセンブリの読み込み
[void][Reflection.Assembly]::LoadWithPartialName("System.Drawing")

# 画像変換に使用するフォルダを定数で定義
$source = "C:\MyPowerShell\practice_folder"
$destination = "C:\MyPowerShell\resize"

# フォルダ一覧の取得
$source_folders = @(Get-ChildItem -Directory $source)

foreach($source_folder in $source_folders){

    # 保存先のフォルダを作成
    $folder_name = $source_folder.Name
    New-Item ("$destination\$folder_name") -ItemType Directory

    # 画像ファイルの取得
    $image_files = $source_folder.GetFiles()
    foreach($image_file in $image_files){
        $image = New-Object System.Drawing.Bitmap($image_file.FullName)

        # ==============================
        # Resize語のWidth, Height を決定
        # ==============================

        $old_width = $image.Width
        $old_height = $image.Height
        $aspect_ratio = ($old_height / $old_width)

        if($old_width -lt 800){
            $w = $old_width
            $h = $old_height
        }
        elseif($old_width -gt $old_height){
            $w = 1200
            $h = ($aspect_ratio * $w)
        }
        else{
            $w = 800
            $h = ($aspect_ratio * $w)
        }


        #======================================================
        # Resizeデータの作成
        #======================================================

        $canvas = New-Object System.Drawing.Bitmap([int]$w, [int]$h)
        $graphics = [System.Drawing.Graphics]::FromImage($canvas)
        $graphics.DrawImage($image, (New-Object System.Drawing.Rectangle(0, 0, $canvas.Width, $canvas.Height)))


        #======================================================
        # 画像の保存
        #======================================================

        $image_name = $image_file.Name
        $canvas.Save("$destination\$folder_name\$image_name", [System.Drawing.Imaging.ImageFormat]::Jpeg)
    }
}

# オブジェクトの破棄
$graphics.Dispose()
$canvas.Dispose()
$image.Dispose()

プログラム実行結果

変換前
 C:\MyPowerShell\practice_folder\folder1\aaa1.jpg
 C:\MyPowerShell\practice_folder\folder1\bbb1.jpg
 C:\MyPowerShell\practice_folder\folder2\aaa2.jpg
 C:\MyPowerShell\practice_folder\folder2\bbb2.jpg

変換後
 ※既存ファイルは残存
 C:\MyPowerShell\resize\folder1\aaa1.jpg
 C:\MyPowerShell\resize\folder1\bbb1.jpg
 C:\MyPowerShell\resize\folder2\aaa2.jpg
 C:\MyPowerShell\resize\folder2\bbb2.jpg

学習したポイント

# 絶対パス取得:絶対パスはBitmapオブジェクトの作成などに用いる
@((Get-ChildItem $source).FullName)
# ファイル名、フォルダ名取得
@((Get-ChildItem $source).Name)
# Get-ChildItemの-Directoryオプション:フォルダのみ取得
@((Get-ChildItem $source).FullName)

 一番重要なのは、公式サイト(MDN)にほぼすべて書いてあること。
 クラスごとのProperty , Method, も丁寧に書いてあるので、個人使用なら資料はそれだけで十分。

おまけ情報

 開発環境:PowerShell ISE
 撮影環境:VSCode