Недавно писал для себя, она правда еще и кропает в квадрат, но это можно убрать, конечно же, добавив математики по вычислению нового размера.
function Resize-Image {
<#
.SYNOPSIS
Resize-Image resizes an image file
.DESCRIPTION
This function uses the native .NET API to resize an image file
.EXAMPLE
Resize the image to a specific size:
Resize-Image -InputFile "C:\userpic.jpg" -OutputFile "C:\userpic-400.jpg"-SquareHeight 400
#>
Param(
[Parameter( Mandatory )]
[string]$InputFile,
[Parameter( Mandatory )]
[string]$OutputFile,
[Parameter( Mandatory )]
[int32]$SquareHeight,
[ValidateRange( 1, 100 )]
[int]$Quality = 85
)
# Add System.Drawing assembly
Add-Type -AssemblyName System.Drawing
# Open image file
$Image = [System.Drawing.Image]::FromFile( $InputFile )
# Create empty square canvas for the new image
# Calculate the offset for centering the image
$Offset = 0
$SquareSide = if ( $Image.Height -lt $Image.Width ) {
$Image.Height
} else {
$Image.Width
$Offset = ( $Image.Height - $Image.Width ) / 4
}
$SquareImage = New-Object System.Drawing.Bitmap( $SquareSide, $SquareSide )
$SquareImage.SetResolution( $Image.HorizontalResolution, $Image.VerticalResolution )
# Draw new image on the empty canvas
$Canvas = [System.Drawing.Graphics]::FromImage( $SquareImage )
$Canvas.DrawImage( $Image, 0, - $Offset )
# Resize image
$ResultImage = New-Object System.Drawing.Bitmap( $SquareHeight, $SquareHeight )
$Canvas = [System.Drawing.Graphics]::FromImage( $ResultImage )
$Canvas.DrawImage( $SquareImage, 0, 0, $SquareHeight, $SquareHeight )
$ImageCodecInfo = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
Where-Object MimeType -eq 'image/jpeg'
# https://msdn.microsoft.com/ru-ru/library/hwkztaft(v=vs.110).aspx
$EncoderQuality = [System.Drawing.Imaging.Encoder]::Quality
$EncoderParameters = New-Object System.Drawing.Imaging.EncoderParameters( 1 )
$EncoderParameters.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter( $EncoderQuality, $Quality )
# Save the image
$ResultImage.Save( $OutputFile, $ImageCodecInfo, $EncoderParameters )
}