我有非常大的图像(jpg),我想写一个csharp程序来循环文件,并将每个图像的大小减少75%.
我试过这个:
Image thumbNail = image.GetThumbnailImage(800, 600, null, new IntPtr());
但文件大小仍然很大.
反正有没有创建缩略图并且文件大小更小?
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)); }
用法:
Image myImg = Image.FromFile(@"C:\Test.jpg"); CompressAndSaveImage(myImg, @"C:\Test2.jpg", 10);
这将压缩Test.jpg的质量为10并将其保存为Test2.jpg.
编辑:作为一种扩展方法可能会更好:
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); }
用法:
Image myImg = Image.FromFile(@"C:\Test.jpg"); myImg.SaveCompressed(@"C:\Test2.jpg", 10);