Skip to content

Instantly share code, notes, and snippets.

@bpatra
Created December 5, 2020 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bpatra/527c52118ca17114ef1e51e52a93d69a to your computer and use it in GitHub Desktop.
Save bpatra/527c52118ca17114ef1e51e52a93d69a to your computer and use it in GitHub Desktop.
Param ( [Parameter(Mandatory=$True)] [ValidateNotNull()] $imageSource, [Parameter(Mandatory=$true)][ValidateNotNull()] $quality )
if (!(Test-Path $imageSource)){throw( "Cannot find the source image")}
if ($quality -lt 0 -or $quality -gt 100){throw( "quality must be between 0 and 100.")}
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$resolvedPath = Join-Path $PWD -ChildPath $imageSource
$bmp = [System.Drawing.Image]::FromFile($resolvedPath)
#hardcoded canvas size...
$canvasWidths = @(200, 400, 600, 800)
foreach($canvasWidth in $canvasWidths){
#Encoder parameter for image quality
$myEncoder = [System.Drawing.Imaging.Encoder]::Quality
$encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1)
$encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter($myEncoder, $quality)
# get codec
$myImageCodecInfo = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders()|where {$_.MimeType -eq 'image/jpeg'}
#compute the final ratio to use
$ratioX = $canvasWidth / $bmp.Width;
$ratioY = $canvasWidth / $bmp.Height;
$ratio = $ratioY
if($ratioX -le $ratioY){
$ratio = $ratioX
}
#create resized bitmap
$newWidth = [int] ($bmp.Width*$ratio)
$newHeight = [int] ($bmp.Height*$ratio)
$bmpResized = New-Object System.Drawing.Bitmap($newWidth, $newHeight)
$graph = [System.Drawing.Graphics]::FromImage($bmpResized)
$graph.Clear([System.Drawing.Color]::White)
$graph.DrawImage($bmp,0,0 , $newWidth, $newHeight)
$targetFileName = [System.IO.Path]::GetFileNameWithoutExtension($imageSource) + "-" + $canvasWidth + ".jpg"
$dir = [System.IO.Path]::GetDirectoryName($resolvedPath)
$targetFilePath = Join-Path $dir -ChildPath $targetFileName
Write-Host "Saving file" $targetFilePath
#save to file
$bmpResized.Save($targetFilePath,$myImageCodecInfo, $($encoderParams))
$graph.Dispose()
$bmpResized.Dispose()
}
$bmp.Dispose()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment