C# .NET - how to compress image - Asked By pankaj singh on 04-Oct-12 02:55 AM

Hi expert
  Please give me any idea that how to compress image using c#
Tejaswini Prashant J replied to pankaj singh on 04-Oct-12 04:58 AM
Hi,
Check the following links..

http://geekswithblogs.net/bullpit/archive/2009/04/29/compress-image-files-using-c.aspx

http://www.c-sharpcorner.com/uploadfile/rahuldebray/compress-image-to-a-given-size/

http://www.codeproject.com/Articles/15884/Compressible-Bitmap-Using-In-Memory-Image-Compress

Hope it will help
joharika reddy replied to pankaj singh on 04-Oct-12 05:03 AM
Hi,

    Try this code may be helpfull..

public static void CompressJpeg(string path, int quality)
{
  if (quality < 0 || quality > 100)
  {
    throw new
      ArgumentOutOfRangeException("Quality must be between 0 and 100.");
  }
  //Creating temp. file and
  string tempFile = Path.GetTempFileName();
  File.Copy(path, tempFile, true);
  using (var image = Image.FromFile(tempFile))
  {
    // Encoder parameter for image quality
    var qualityParam =
      new EncoderParameter(Encoder.Quality, quality);
    // Jpeg image codec
    var jpegCodec = ImageCodecInfo.GetImageEncoders()
      .Where(imageCodecInfo => imageCodecInfo.MimeType == "image/jpeg")
      .FirstOrDefault();
    var encoderParams = new EncoderParameters(1);
    encoderParams.Param[0] = qualityParam;
    //Save the compressed image.
    image.Save(path, jpegCodec, encoderParams);
    //Getting the file image sizes.
    var prevImageSize = new FileInfo(tempFile).Length;
    var nextImageSize = new FileInfo(path).Length;
    Console.WriteLine("Image compressed. Size saved :{0} bytes",
      prevImageSize - nextImageSize);
  }
  //Removing the temp. file.
  File.Delete(tempFile);
}
pankaj singh replied to joharika reddy on 04-Oct-12 09:31 AM
this is help full for me.. Greate..