AKZN Notes

Archives for My Lazy and Forgetful Mind

Batch resize image on windows 11 using powershell

This script below work as

  1. resize all image with jpg, jpeg, JPG, JPEG extension inside folder and subfolder
  2. save the result into 'web' folder at same folder as this script
  1. make file with ps1 extension
    Add-Type -AssemblyName System.Drawing

    $w = 300
    $h = 400
    $quality = 70  # JPEG quality 0–100
    $root = Get-Location
    $outDir = Join-Path $root "web"

    if (!(Test-Path $outDir)) { New-Item -ItemType Directory -Path $outDir | Out-Null }

    # get JPEG encoder
    $jpegCodec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
        Where-Object { $_.MimeType -eq 'image/jpeg' }

    # process jpg and jpeg (case-insensitive)
    Get-ChildItem -Path $root -Recurse -Include *.jpg,*.jpeg | ForEach-Object {
        $img = [System.Drawing.Image]::FromFile($_.FullName)

        $bmp = New-Object System.Drawing.Bitmap $w, $h
        $gr = [System.Drawing.Graphics]::FromImage($bmp)
        $gr.DrawImage($img, 0, 0, $w, $h)

        $dest = Join-Path $outDir $_.Name

        $img.Dispose()
        $gr.Dispose()

        # set quality
        $encParam = New-Object System.Drawing.Imaging.EncoderParameters(1)
        $encParam.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter(
            [System.Drawing.Imaging.Encoder]::Quality, $quality
        )

        $bmp.Save($dest, $jpegCodec, $encParam)
        $bmp.Dispose()
    }
  1. run with on the same folder as this script with
    owershell -ExecutionPolicy Bypass -File resize.ps1

Leave a Reply

Your email address will not be published.