Thursday, April 12, 2012

Compress uploaded Image using Asp.net

This code show you how to resize the image without disturbing image quality
By resizing we can increase the site performance
Image width * Height remain same but its size get change
ex: 815 mb to 118 mb
Code


In .aspx page
  <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
  <asp:Button ID="btncompress" runat="server" Text="Button" />


In .vb page
 Protected Sub  btncompress_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles  btncompress.Click


        Dim oImg As System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath("actualimage/" + FileUpload1.FileName))
        Dim oThumbNail As System.Drawing.Image = New System.Drawing.Bitmap(Convert.ToInt32(oImg.Width), Convert.ToInt32(oImg.Height))
        ', System.Drawing.Imaging.PixelFormat.Format24bppRgb
        Dim oGraphic As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(oThumbNail)
        oGraphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        'set smoothing mode to high quality
        oGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        'set the interpolation mode
        oGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
        'set the offset mode
        oGraphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality


        Dim oRectangle As New System.Drawing.Rectangle(0, 0, Convert.ToInt32(oImg.Width), Convert.ToInt32(oImg.Height))
        oGraphic.DrawImage(oImg, oRectangle)
        Dim ext As String
        ext = Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower()
        
        oThumbNail.Save(Server.MapPath("compressimage/" + FileUpload1.FileName), System.Drawing.Imaging.ImageFormat.Jpeg)
        oImg.Dispose()


    End Sub


For croping image see: View Example




No comments:

Post a Comment