Compress JPEG Image using C#

by gayancc13. January 2012 23:46

Recently I had to make some photo upload task with compression enabled I thought to share the code that I used on my project. The code will help you to compress the JPEG images using C#. here is the code snippet.

public static void CompressImage(string path, int quality)
{
if (quality < 0 || quality > 100)
{
throw new
ArgumentOutOfRangeException("Quality must be between 0 and 100.");
}
string tmp = Path.GetTempFileName();
File.Copy(path, tmp, true);using (var image = Image.FromFile(tmp))
{
var qualityParam =
new EncoderParameter(Encoder.Quality, quality);
var jpgCdc = ImageCodecInfo.GetImageEncoders()
.Where(imageCodecInfo => imageCodecInfo.MimeType == "image/jpeg")
.FirstOrDefault();
var encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
image.Save(path, jpgCdc, encoderParams);
var prevImageSize = new FileInfo(tmp).Length;
var nextImageSize = new FileInfo(path).Length;
Console.WriteLine("Image compressed. Size saved :{0} bytes",
prevImageSize - nextImageSize);
}
File.Delete(tmp);
}

Happy Coding :)

Tags:

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading