Create thumbnail and reduce image size
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);
ImageMagick is a command line tool which is hugely powerful for doing image manipulation. I've used it for resizing large images and thumbnail creation in circumstances where the aspect ratio of the source image is unknown or is unreliable. ImageMagick is able to resize images to a specific height or width while maintaining the original aspect ratio of your picture. It can also add space around an image if required. All in all very powerful and a nice abstraction from having to deal with .nets Image APIs. To use the imageMagick command line tool from within C# I recommend using the System.Diagnostics.ProcessStartInfo object like so:
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = @"C:\Program Files\ImageMagick-6.5.0-Q16\convert.exe";
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.Arguments = string.Format("-size x{0} \"{1}\" -thumbnail 200x140 -background transparent -gravity center -extent 200x140 \"{2}\"", heightToResizeTo, originalTempFileLocation, resizedTempFileLocation);
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.WaitForExit();
Using the scale% paramater you can easily reduce the size of your image by 75%