Skip to content

Instantly share code, notes, and snippets.

@mortenya
Last active July 12, 2023 17:01
Show Gist options
  • Save mortenya/48eabd2f52206eecc10330da73de1bf0 to your computer and use it in GitHub Desktop.
Save mortenya/48eabd2f52206eecc10330da73de1bf0 to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Resize photos to a specified size, 648 by default
Rename them and place them in a 'resized' folder
.EXAMPLE
Get-ChildItem -Path C:\Picures | Resize-ThumbnailPhoto
#>
Function Resize-ThumbnailPhoto
{
param(
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipeline = $true)]
$ImagePath,
[Parameter(Mandatory = $false)]
[int]$targetSize = 648,
[Parameter(Mandatory = $false)]
[int]$Quality = 85,
[Parameter(Mandatory = $false)]
$OutputFile = "$($ImagePath.DirectoryName)\resized\$($ImagePath.BaseName).jpg"
)
Begin
{
Add-Type -AssemblyName "System.Drawing"
# Get the desired image codec
# MimeType: image/bmp, image/jpeg, image/gif, image/tiff, image/png
$Codec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where {$_.MimeType -eq 'image/jpeg'}
#Encoder parameter for image quality
$ImageEncoder = [System.Drawing.Imaging.Encoder]::Quality
#create the EncoderParameters object
$encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1)
$encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter($ImageEncoder, $Quality)
}
Process
{
Write-Verbose "Working on - $($ImagePath.FullName)"
# Initialize an object for the image
$img = [System.Drawing.Image]::FromFile($($ImagePath.FullName))
#compute the final ratio to use
$ratioX = $targetSize / $img.Width;
$ratioY = $targetSize / $img.Height;
$ratio = $ratioY
if ($ratioX -le $ratioY) {
$ratio = $ratioX
}
# Set the new width and height based on the ratio
$newWidth = [int] ($img.Width * $ratio)
$newHeight = [int] ($img.Height * $ratio)
# Create the canvas for resized image and then draw it to fit
$bmpResized = New-Object System.Drawing.Bitmap($newWidth, $newHeight)
$graph = [System.Drawing.Graphics]::FromImage($bmpResized)
$graph.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$graph.Clear([System.Drawing.Color]::White)
$graph.DrawImage($img, 0, 0, $newWidth, $newHeight)
}
End
{
Write-Verbose "Saving to - $($OutputFile)"
#save to file
$bmpResized.Save($OutputFile, $Codec, $($encoderParams))
$bmpResized.Dispose()
$img.Dispose()
}
}
<#
Get-ChildItem -Path "\\path\to\thumbnailPhotos" -Depth 0 -Filter '*.jpg' | % {
if ($_.Length -gt 99000) { Resize-ThumbnailPhoto -ImagePath $_ }
}
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment