Điều này sẽ thay đổi kích thước bất kỳ hình ảnh bằng cách sử dụng chất lượng tốt nhất với sự hỗ trợ cho 32bpp với alpha. Hình ảnh mới sẽ có hình ảnh gốc được căn giữa bên trong hình ảnh mới với tỷ lệ khung hình gốc.
#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
Nguồn
2013-03-11 19:41:30
'Drawing2D.SmoothingMode' không áp dụng ở đây, nó chỉ thích hợp cho 2D vẽ vector các phương thức như 'Graphics.DrawLine' – alldayremix
Hãy cẩn thận với điều này. Phần 'With grDest' xuất hiện để tăng giá trị alpha từng chút một, chỉ đáng chú ý khi xử lý lặp lại cùng một hình ảnh với phần tử bán mờ cho hình ảnh. Theo thời gian, điều này trở nên ít mờ nhạt hơn. Tôi đã nhận xét phần .SmoothingMode và Thay đổi CompositingMode thành SourceCopy. Vẫn đang thử nghiệm nhưng một trong hai dường như đã thực hiện nó. Sợ tôi không thể đưa ra câu trả lời chính xác vì không hiểu rõ GDI. Có thể @Carter có thể giúp tiếp tục đưa ra kiến thức về GDI của anh ấy. – stigzler