原本宽度为300 的图片ImagePhoto 大小为 30KB
FixedSize(ImagePhoto,300) 之后 图片 变为 20KB 了,图片质量下降了很多
怎么弄让图片质量和原来的一样呢?
public static Image FixedSize(Image imgPhoto, int Width)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int w, h;
if (sourceWidth > Width)
{
decimal nPercent = (decimal)sourceWidth / Width;
w = Width;
h = (int)Math.Round((decimal)sourceHeight / nPercent, 0);
}
else
{
w = sourceWidth;
h = sourceHeight;
}
Bitmap bmPhoto = new Bitmap(w, h, imgPhoto.PixelFormat);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.CompositingQuality = CompositingQuality.HighQuality;
grPhoto.SmoothingMode = SmoothingMode.HighQuality;
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(0, 0, w, h),
new Rectangle(0, 0, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
如果是JPG的话,参考以下代码:
var imageCodeInfo = GetEncoderInfo("image/jpeg");
var myEncoder = System.Drawing.Imaging.Encoder.Quality;
var myEncoderParameters = new EncoderParameters(1);
var myEncoderParameters.Param[0] = new EncoderParameter(myEncoder, 99L);
thumbNail.Save(thumbUrl, imageCodeInfo, myEncoderParameters);
非常感谢,就是这样