Spowoduje to ponowne rozmiar dowolny obraz przy użyciu najlepszej jakości ze wsparciem dla 32 bity na piksel z alfa. Nowy obraz będzie miał oryginalny obraz wyśrodkowany wewnątrz nowego w oryginalnym formacie obrazu.
#Region " ResizeImage "
Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmSource = New Drawing.Bitmap(SourceImage)
Return ResizeImage(bmSource, TargetWidth, TargetHeight)
End Function
Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)
Dim nSourceAspectRatio = bmSource.Width/bmSource.Height
Dim nDestAspectRatio = bmDest.Width/bmDest.Height
Dim NewX = 0
Dim NewY = 0
Dim NewWidth = bmDest.Width
Dim NewHeight = bmDest.Height
If nDestAspectRatio = nSourceAspectRatio Then
'same ratio
ElseIf nDestAspectRatio > nSourceAspectRatio Then
'Source is taller
NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth)/2))
Else
'Source is wider
NewHeight = Convert.ToInt32(Math.Floor((1/nSourceAspectRatio) * NewWidth))
NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight)/2))
End If
Using grDest = Drawing.Graphics.FromImage(bmDest)
With grDest
.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver
.DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
End With
End Using
Return bmDest
End Function
#End Region
'Drawing2D.SmoothingMode' nie ma tu zastosowania, to jest istotne tylko dla 2D wektorowej metody takie jak 'Graphics.DrawLine' – alldayremix
Ostrożnie z tym. Sekcja 'With grDest' wydawała się tak nieznacznie zwiększać wartości alfa, zauważalne tylko w iteracyjnym przetwarzaniu tego samego obrazu z elementem półprzezroczystym do obrazu. Z biegiem czasu stało się to coraz mniej nieprzejrzyste. Skomentowałem część .SmoothingMode i Changed CompositingMode do SourceCopy. Wciąż testowałem, ale zdaje się, że zrobił to jeden z nich. Obawiam się, że nie mogę podać dokładnej odpowiedzi, ponieważ nie rozumiem tak dobrze GDI. Może @Carter może być w stanie pomóc dalej, biorąc pod uwagę jego wiedzę na temat GDI. – stigzler