📸

PowerShell で iPhone の画像の回転を元に戻す

に公開

iPhone で撮影した写真は、縦横が逆になってしまう場合があります。検索すると多くの情報が見つかりますが、これは Exif 情報を認識して回転しないことが原因です。煩わしい場合は、Exif に従って画像自体を回転させることで対応できます。C# での情報もありますが、C# で書くほどでもないため、PowerShell で実装してみました。こちらのスクリプトを ps1 ファイルとして保存し、実行することで解決できます。

https://smdn.jp/programming/netfx/tips/rotate_image_by_exif_info

[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.IO")

$sourceDir = "{{source-folder}}"
$destDir = "{{dest-folder}}"

foreach ($sourceFile in [System.IO.Directory]::GetFiles($sourceDir, "*")) {

    $destFile = [System.IO.Path]::Combine($destDir, [System.IO.Path]::GetFileName($sourceFile))

    $origin = New-Object System.Drawing.Bitmap($sourceFile)
    $rotation = [System.Drawing.RotateFlipType]::RotateNoneFlipNone

    foreach ($item in $origin.PropertyItems) {
        if ($item.Id -eq 274) {
            if ($item.Value[0] -eq 3) {
                $rotation = [System.Drawing.RotateFlipType]::Rotate180FlipNone
            }
            if ($item.Value[0] -eq 6) {
                $rotation = [System.Drawing.RotateFlipType]::Rotate90FlipNone
            }
            if ($item.Value[0] -eq 8) {
                $rotation = [System.Drawing.RotateFlipType]::Rotate270FlipNone
            }
        }
    }

    $rotated = [System.Drawing.Bitmap]$origin.Clone()
    $rotated.RotateFlip($rotation)
    foreach ($item in $origin.PropertyItems) {
        if ($item.Id -eq 274) {
            $item.Value[0] = 0
            $rotated.SetPropertyItem($item)
        }
    }

    $rotated.Save($destFile, [System.Drawing.Imaging.ImageFormat]::Jpeg)

    $origin.Dispose()
    $rotated.Dispose()

}

Discussion