/ Published in: VB.NET
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
Public Class SaveResizedImage ' SaveResizedImage Public Sub SaveResizedImage(ByVal objGraphic As System.Drawing.Image, ByVal strPath As String, ByVal intWidth As Integer) Dim objFormat As System.Drawing.Imaging.ImageFormat = objGraphic.RawFormat Dim objThumbSize As New System.Drawing.Size objThumbSize = GetSize(objGraphic.Width, objGraphic.Height, intWidth) Dim objBmp As System.Drawing.Bitmap = CreateThumbnail(objGraphic, objThumbSize.Width, objThumbSize.Height) If objFormat Is System.Drawing.Imaging.ImageFormat.Gif Then objBmp.Save(strPath, System.Drawing.Imaging.ImageFormat.Gif) Else objBmp.Save(strPath, System.Drawing.Imaging.ImageFormat.Jpeg) End If objBmp.Dispose() End Sub ' SaveResizedImage ' GetSize Private Function GetSize(ByVal dblWidth As Double, ByVal dblHeight As Double, ByVal intWidth As Integer) As System.Drawing.Size Dim dblNewWidth As Double Dim dblNewHeight As Double dblNewWidth = intWidth ' Set new height, preserve original width/height ratio dblNewHeight = dblHeight * dblNewWidth / dblWidth Dim NewSize As New System.Drawing.Size(CInt(dblNewWidth), CInt(dblNewHeight)) Return NewSize End Function ' GetSize ' CreateThumbnail Private Function CreateThumbnail(ByVal objGraphic As System.Drawing.Image, ByVal lnWidth As Integer, ByVal lnHeight As Integer) As System.Drawing.Bitmap Dim bmpOut As System.Drawing.Bitmap = Nothing Try Dim loBMP As New System.Drawing.Bitmap(objGraphic) Dim loFormat As System.Drawing.Imaging.ImageFormat = loBMP.RawFormat Dim lnRatio As Decimal Dim lnNewWidth As Integer = 0 Dim lnNewHeight As Integer = 0 If loBMP.Width < lnWidth AndAlso loBMP.Height < lnHeight Then Return loBMP End If If loBMP.Width > loBMP.Height Then lnRatio = CType(lnWidth, Decimal) / loBMP.Width lnNewWidth = lnWidth Dim lnTemp As Decimal = loBMP.Height * lnRatio lnNewHeight = CType(lnTemp, Integer) Else lnRatio = CType(lnHeight, Decimal) / loBMP.Height lnNewHeight = lnHeight Dim lnTemp As Decimal = loBMP.Width * lnRatio lnNewWidth = CType(lnTemp, Integer) End If bmpOut = New System.Drawing.Bitmap(lnNewWidth, lnNewHeight) Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpOut) g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic g.FillRectangle(System.Drawing.Brushes.White, 0, 0, lnNewWidth, lnNewHeight) g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight) loBMP.Dispose() Catch Return Nothing End Try Return bmpOut End Function ' CreateThumbnail End Class