How to compress a JPG image using .net code

Sunday 7 December 2014

How to compress a JPG image using .net code

Use the below code to compress a jpg image 


Imports System.Drawing
Imports System.Drawing.Imaging

 Public Sub Compress(ByVal imgPath As String)
        Dim oBitmap As Bitmap
        oBitmap = New Bitmap(imgPath)

        Dim oGraphic As Graphics
        ' Here create a new bitmap object of the same height and width of the image.
        ' Dim bmpNew As Bitmap = New Bitmap(oBitmap.Width, oBitmap.Height)
        Dim bmpNew As Bitmap = New Bitmap(800, 1200)
        oGraphic = Graphics.FromImage(bmpNew)
        oGraphic.DrawImage(oBitmap, New Rectangle(0, 0, _
     bmpNew.Width, bmpNew.Height), 0, 0, oBitmap.Width, _
      oBitmap.Height, GraphicsUnit.Pixel)
        ' Release the lock on the image file. Of course,
        ' image from the image file is existing in Graphics object
        oBitmap.Dispose()
        oBitmap = bmpNew

        Dim oBrush As New SolidBrush(Color.Black)
        ' Dim ofont As New Font("Arial", 8)
        ' oGraphic.DrawString("Some text to write", ofont, oBrush, 10, 10)
        oGraphic.Dispose()
        ' ofont.Dispose()
        oBrush.Dispose()
        oBitmap.Save(imgPath, ImageFormat.Jpeg)
        oBitmap.Dispose()
    End Sub