/// <summary> /// 图片转换 /// </summary> /// <param name="image"></param> /// <param name="directoryPath">目录路径</param> /// <param name="imageenum"></param> /// <param name="qualityNum">图片质量</param> public Image ImageTransformation(Image image, string directoryPath, ImageFormatEnum imageenum,long qualityNum=100) { int oldWidth = image.Width; int oldHeight = image.Height; int newWidth = 0; int newHeight = 0; if (oldWidth > oldHeight && oldWidth > (int)imageenum) { newWidth = (int)imageenum; newHeight = Convert.ToInt32(oldHeight * newWidth / oldWidth); } else if (oldHeight > oldWidth && oldHeight > (int)imageenum) { newHeight = (int)imageenum; newWidth = Convert.ToInt32(oldWidth * newHeight / oldHeight); } else if (oldWidth == oldHeight && oldWidth > (int)imageenum) { newHeight = (int)imageenum; newWidth = Convert.ToInt32(oldWidth * newHeight / oldHeight); } else { newWidth = Convert.ToInt32(oldWidth); newHeight = Convert.ToInt32(oldHeight); } //新建图片 Image bitmap = new Bitmap(newWidth, newHeight); //新建画板 Graphics g = Graphics.FromImage(bitmap); //清空画布并设置背景色 g.Clear(Color.Transparent); //设置画布的绘画质量 g.CompositingQuality = CompositingQuality.HighQuality; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.HighQuality; //设置高质量插值法 g.InterpolationMode = InterpolationMode.HighQualityBilinear; //显示图像的位置 Rectangle destRect = new Rectangle(0, 0, newWidth, newHeight); //显示图像那一部分 Rectangle srcRect = new Rectangle(0, 0, image.Width, image.Height); g.DrawImage(image, destRect, srcRect, GraphicsUnit.Pixel); g.Dispose(); //以下代码为保存图片时,设置压缩质量 EncoderParameters encoderParams = new EncoderParameters(); EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, qualityNum); encoderParams.Param[0] = encoderParam; string imgname = _context.Server.MapPath("/") + directoryPath + "/" + imageenum.ToString() + ".jpeg"; bitmap.Save(imgname, GetEncoderInfo("image/jpeg"), encoderParams); bitmap.Dispose(); return bitmap; } 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; } /// <summary> /// 图片格式 /// </summary> public enum ImageFormatEnum { _60 = 60, _90 = 90, _160 = 160, _220 = 220, _m = 400, _660 = 660, _800 = 800, _1200 = 1200, _b = 0 //原图 }