Save Resized Image Class


SUBMITTED BY: Guest

DATE: Oct. 28, 2013, 1:06 p.m.

FORMAT: Text only

SIZE: 3.3 kB

HITS: 885

  1. VB.NET Code:
  2. Public Class SaveResizedImage
  3. ' SaveResizedImage
  4. Public Sub SaveResizedImage(ByVal objGraphic As System.Drawing.Image, ByVal strPath As String, ByVal intWidth As Integer)
  5. Dim objFormat As System.Drawing.Imaging.ImageFormat = objGraphic.RawFormat
  6. Dim objThumbSize As New System.Drawing.Size
  7. objThumbSize = GetSize(objGraphic.Width, objGraphic.Height, intWidth)
  8. Dim objBmp As System.Drawing.Bitmap = CreateThumbnail(objGraphic, objThumbSize.Width, objThumbSize.Height)
  9. If objFormat Is System.Drawing.Imaging.ImageFormat.Gif Then
  10. objBmp.Save(strPath, System.Drawing.Imaging.ImageFormat.Gif)
  11. Else
  12. objBmp.Save(strPath, System.Drawing.Imaging.ImageFormat.Jpeg)
  13. End If
  14. objBmp.Dispose()
  15. End Sub ' SaveResizedImage
  16. ' GetSize
  17. Private Function GetSize(ByVal dblWidth As Double, ByVal dblHeight As Double, ByVal intWidth As Integer) As System.Drawing.Size
  18. Dim dblNewWidth As Double
  19. Dim dblNewHeight As Double
  20. dblNewWidth = intWidth
  21. ' Set new height, preserve original width/height ratio
  22. dblNewHeight = dblHeight * dblNewWidth / dblWidth
  23. Dim NewSize As New System.Drawing.Size(CInt(dblNewWidth), CInt(dblNewHeight))
  24. Return NewSize
  25. End Function ' GetSize
  26. ' CreateThumbnail
  27. Private Function CreateThumbnail(ByVal objGraphic As System.Drawing.Image, ByVal lnWidth As Integer, ByVal lnHeight As Integer) As System.Drawing.Bitmap
  28. Dim bmpOut As System.Drawing.Bitmap = Nothing
  29. Try
  30. Dim loBMP As New System.Drawing.Bitmap(objGraphic)
  31. Dim loFormat As System.Drawing.Imaging.ImageFormat = loBMP.RawFormat
  32. Dim lnRatio As Decimal
  33. Dim lnNewWidth As Integer = 0
  34. Dim lnNewHeight As Integer = 0
  35. If loBMP.Width < lnWidth AndAlso loBMP.Height < lnHeight Then
  36. Return loBMP
  37. End If
  38. If loBMP.Width > loBMP.Height Then
  39. lnRatio = CType(lnWidth, Decimal) / loBMP.Width
  40. lnNewWidth = lnWidth
  41. Dim lnTemp As Decimal = loBMP.Height * lnRatio
  42. lnNewHeight = CType(lnTemp, Integer)
  43. Else
  44. lnRatio = CType(lnHeight, Decimal) / loBMP.Height
  45. lnNewHeight = lnHeight
  46. Dim lnTemp As Decimal = loBMP.Width * lnRatio
  47. lnNewWidth = CType(lnTemp, Integer)
  48. End If
  49. bmpOut = New System.Drawing.Bitmap(lnNewWidth, lnNewHeight)
  50. Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpOut)
  51. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
  52. g.FillRectangle(System.Drawing.Brushes.White, 0, 0, lnNewWidth, lnNewHeight)
  53. g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight)
  54. loBMP.Dispose()
  55. Catch
  56. Return Nothing
  57. End Try
  58. Return bmpOut
  59. End Function ' CreateThumbnail
  60. End Class

comments powered by Disqus