/// <summary> /// 高质量缩放图片 /// </summary> /// <param name="OriginFilePath">源图的路径</param> /// <param name="TargetFilePath">存储缩略图的路径</param> /// <param name="DestWidth">缩放后图片宽度</param> /// <param name="DestHeight">缩放后图片高度</param> /// <returns>表明此次操作是否成功</returns> public static bool ToSuolue(System.IO.Stream oStream, string TargetFilePath, int towidth, int toheight) { //System.Drawing.Image OriginImage = System.Drawing.Image.FromFile(OriginFilePath); System.Drawing.Image OriginImage = System.Drawing.Image.FromStream(oStream); System.Drawing.Imaging.ImageFormat thisFormat = OriginImage.RawFormat; //按比例缩放 int x = 0, y = 0; int ow = OriginImage.Width; int oh = OriginImage.Height; if ((double)ow / (double)oh > (double)towidth / (double)toheight) { oh = OriginImage.Height; ow = OriginImage.Height * towidth / toheight; y = 0; x = (OriginImage.Width - ow) / 2; } else { ow = OriginImage.Width; oh = OriginImage.Width * toheight / towidth; x = 0; y = (OriginImage.Height - oh) / 2; } Bitmap bt = new Bitmap(towidth, toheight); //根据指定大小创建Bitmap实例 using (Graphics g = Graphics.FromImage(bt)) { g.Clear(Color.White); //设置画布的描绘质量 g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(OriginImage, new Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); g.Dispose(); } System.Drawing.Imaging.EncoderParameters EncoderParams = new System.Drawing.Imaging.EncoderParameters(); //取得内置的编码器 long[] Quality = new long[1]; Quality[0] = 100; System.Drawing.Imaging.EncoderParameter EncoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality); EncoderParams.Param[0] = EncoderParam; //try //{ //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象 System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.ImageCodecInfo jpegICI = null; for (int i = 0; i < arrayICI.Length; i++) { if (arrayICI[i].FormatDescription.Equals("JPEG")) { jpegICI = arrayICI[i]; //设置为JPEG编码方式 break; } } if (jpegICI != null) //保存缩略图 { bt.Save(TargetFilePath, jpegICI, EncoderParams); } else { bt.Save(TargetFilePath, thisFormat); } OriginImage.Dispose(); return true; //} //catch (System.Runtime.InteropServices.ExternalException e1) //GDI+发生一般错误 //{ // return false; //} //catch (Exception e2) //{ // return false; //} }