Answer the question
In order to leave comments, you need to log in
Image resizing feature?
Hello.
There is a task to resize an image in .jpg
format
Function Resize-Image
{
param(
[String]$InputFile,
[String]$OutputFile,
[int]$Width,
[int]$Height
)
[reflection.assembly]::LoadWithPartialName("System.Drawing")
$OriginImage = [System.Drawing.Bitmap]::FromFile($InputFile)
$ResizedImage = New-Object System.Drawing.Bitmap @($Width, $Height)
$graphics = [System.Drawing.Graphics]::FromImage($ResizedImage)
$graphics.DrawImage($OriginImage, 0, 0, $Width, $Height)
$graphics.Dispose()
$ResizedImage.Save($OutputFile)
}
Answer the question
In order to leave comments, you need to log in
Recently I wrote for myself, it’s true that it also sprinkles into a square, but this can be removed, of course, by adding mathematics to calculate the new size.
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 )
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question