Skip to content

Instantly share code, notes, and snippets.

@lukemv
Created August 8, 2017 06:34
Show Gist options
  • Save lukemv/57264d0563545b0ac51dc6476e28f536 to your computer and use it in GitHub Desktop.
Save lukemv/57264d0563545b0ac51dc6476e28f536 to your computer and use it in GitHub Desktop.
Resize Images using Powershell
## Usage
# cd thebasepath
# .\resize.ps1
function Resize-Image
{
<#
.EXAMPLE
Resize-Image -InputFile "C:\kitten.jpg" -Scale 30 -OutputFile "C:\kitten2.jpg"
Resize the image to 30% of its original size and save it to a new file.
#>
Param(
[Parameter(Mandatory=$true)][string]$InputFile,
[Parameter(Mandatory=$true)][string]$OutputFile,
[Parameter(Mandatory=$true)][int32]$Scale)
# Add System.Drawing assembly
Add-Type -AssemblyName System.Drawing
# Open image file
$img = [System.Drawing.Image]::FromFile((Get-Item $InputFile))
# Define new resolution
[int32]$new_width = $img.Width * ($Scale / 100)
[int32]$new_height = $img.Height * ($Scale / 100)
# Create empty canvas for the new image
$img2 = New-Object System.Drawing.Bitmap($new_width, $new_height)
# Draw new image on the empty canvas
$graph = [System.Drawing.Graphics]::FromImage($img2)
$graph.DrawImage($img, 0, 0, $new_width, $new_height)
$graph.Dispose()
$img.Dispose()
$img2.Save($OutputFile)
$img2.Dispose()
}
$allfiles = Get-ChildItem -Recurse |
Where { $_.PsIsContainer -ieq $false } |
Where { $_.Name.Contains("jpg") -or $_.Name.Contains("jpeg") }
foreach($file in $allfiles) {
$saveTarget = $file.FullName
$tempTarget = $file.FullName + ".temp"
Write-Host "[Info] processor - Processing $saveTarget"
Resize-Image -InputFile $saveTarget -OutputFile $tempTarget -Scale 50
Write-Host "[Info] processor - Replacing file $saveTarget"
Remove-Item $saveTarget -Force
Move-Item $tempTarget $saveTarget
Write-Host "[Info] processor - Sucessfully processed $saveTarget"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment