///调用事例
private void button5_Click(object sender, EventArgs e)
{ string pathPerc = @"E:\XX.jpg";//保存图片地址,名称和格式 string source = @"D\XX.jpg";//图片源文件路径 getThumImage(source, 50, 2, pathPerc);//quality,multiple越小压缩图片越大}
/**/
/// <summary> /// 生成缩略图 /// </summary> /// <param name="sourceFile">原始图片文件</param> /// <param name="quality">质量压缩比</param> /// <param name="multiple">收缩倍数</param> /// <param name="outputFile">输出文件名</param> /// <returns>成功返回true,失败则返回false</returns> public static bool getThumImage(String sourceFile, long quality, int multiple, String outputFile) { try { long imageQuality = quality; Bitmap sourceImage = new Bitmap(sourceFile); ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg"); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality); myEncoderParameters.Param[0] = myEncoderParameter; float xWidth = sourceImage.Width; float yWidth = sourceImage.Height; Bitmap newImage = new Bitmap((int)(xWidth / multiple), (int)(yWidth / multiple)); Graphics g = Graphics.FromImage(newImage);g.DrawImage(sourceImage, 0, 0, xWidth / multiple, yWidth / multiple);
g.Dispose(); newImage.Save(outputFile, myImageCodecInfo, myEncoderParameters); return true; } catch (Exception ex) { return false; } } private static ImageCodecInfo GetEncoderInfo(String mimeType) { int j; ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; }
原文来至:http://blog.csdn.net/szstephenzhou/article/details/38900345