Image Compression in ASP.NET using C#


This is an example for Image compression in ASP.NET using C#. System.Drawing.Imaging Namespace is used and class EncoderParameter, Encoder and EncoderParameters are used to compress the given image. Image compression will reduce the Bandwidth usage in the networks and can be sent quickly via mails.

Design


To get the image from user Place a file upload control and a button in the design and create onclick event called protected void Button3_Click() in code behind file,


<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" oolTip="Upload image" />
<asp:Button ID="Button3" runat="server" nclick="Button3_Click" Text="Load" ForeColor="#003366" />
</div>

</form>



Code behind file for compress the uploaded image:



//Use the following Namespaces

using System.Drawing;
using System.IO;
using System;
using System.Drawing.Imaging;

//Mention the path to store the uploaded image

string Path = @"Your Path";


in the onclick event store the image and convert into bitmap type. then call the imgcompression method to compress the image

protected void Button3_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs(ImagePath);
string imgpath = Path.Combine( Path, FileUpload1.FileName);
Bitmap img = new Bitmap(imgpath);
imgcompression(img);
}


Compress your image to various quality. Encoder Quality range zero is low quality and 100 is high quality.
Here you can get different qualities of a image using EncoderParameter, Encoder and EncoderParameters classes


static void imgcompression(Image img_in)
{

ImageCodecInfo jpeg = null;
ImageCodecInfo[] imgtypes = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo jpegtype in imgtypes)
{
if (jpegtype.FormatID == ImageFormat.Jpeg.Guid)
{
EncoderParameters encParams = new EncoderParameters(1);

for (long quality_rate= 10; quality_rate<= 100; quality_rate+=10)
{
EncoderParameter encParam = new EncoderParameter(Encoder.Quality, quality_rate);
encParams.Param[0] = encParam;
string strPath = Path.Combine(imgPath, "" + quality + ".jpeg");
FileStream fs = new FileStream(strPath, FileMode.Create, FileAccess.Write);
img_in.Save(fs, jpgEncoder, encParams);
fs.Flush();
fs.Close();
}
}

}
}


Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: