Skip to content

Instantly share code, notes, and snippets.

@Liandriz
Created March 27, 2016 01:32
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 Liandriz/2efe0ef1f305e5ad032d to your computer and use it in GitHub Desktop.
Save Liandriz/2efe0ef1f305e5ad032d to your computer and use it in GitHub Desktop.
param([int]$maxsize = 3840,[string]$folder = ".");
Get-ChildItem $folder -include *.jpg,*.jpe,*.jpeg,*.png -recurse -File | ForEach-Object {
$ext =$_.Extension;
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$image = [System.Drawing.Image]::FromFile($_.FullName)
if ($image.width -gt $maxsize -or $image.height -gt $maxsize) {
$ImageEncoder = [System.Drawing.Imaging.Encoder]::Quality
$encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1)
$encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter($ImageEncoder, 100)
If ($ext -eq ".png")
{$Codec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where {$_.MimeType -eq 'image/png'}}
Else {$Codec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where {$_.MimeType -eq 'image/jpeg'}}
$ratioX = $maxsize / $image.Width;
$ratioY = $maxsize / $image.Height;
if($ratioX -le $ratioY){
$ratio = $ratioX
}
else {
$ratio = $ratioY
}
$newWidth = [int] ($image.Width*$ratio)
$newHeight = [int] ($image.Height*$ratio)
$imageResized = New-Object System.Drawing.Bitmap($newWidth, $newHeight)
$imageGraph = [System.Drawing.Graphics]::FromImage($imageResized)
$imageGraph.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$imageGraph.Clear([System.Drawing.Color]::White)
$imageGraph.DrawImage($image,0,0 , $newWidth, $newHeight)
$imageGraph.Dispose()
$image.Dispose()
$imageResized.Save($_, $Codec, $($encoderParams))
$imageResized.Dispose()
write-host "Resized: $_"
}
If ($ext -eq ".png")
{PngOptimizerCL -file:"$_"; write-host "PNG: $_";}
Else {jpegtran -copy none -optimize -progressive -outfile $_ $_; write-host "JPG: $_";}
};
@Liandriz
Copy link
Author

.\resize.ps1 [max-size:3840] [folder:"."]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment