private void CompressAndSaveImage(Image img, string fileName,
long quality) {
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
img.Save(fileName, GetCodecInfo("image/jpeg"), parameters);
}
private static ImageCodecInfo GetCodecInfo(string mimeType) {
foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders())
if (encoder.MimeType == mimeType)
return encoder;
throw new ArgumentOutOfRangeException(
string.Format("'{0}' not supported", mimeType));
}
Usage:
Image myImg = Image.FromFile(@"C:\Test.jpg");
CompressAndSaveImage(myImg, @"C:\Test2.jpg", 10);
That will compress Test.jpg with a quality of 10 and save it as Test2.jpg.
EDIT: Might be better as an extension method:
private static void SaveCompressed(this Image img, string fileName,
long quality) {
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
img.Save(fileName, GetCodecInfo("image/jpeg"), parameters);
}
Usage:
Image myImg = Image.FromFile(@"C:\Test.jpg");
myImg.SaveCompressed(@"C:\Test2.jpg", 10);