我发现当使用 System.Drawing.Graphics 类调整图像大小时,结果图像从右边框和下边框丢失了一个像素。这是我的代码中某处的错误或 .Net 问题?测试代码:
public static void Resize(string imagePath,int width) {
InterpolationMode[] interpolationModes = new InterpolationMode[]{InterpolationMode.Bicubic, InterpolationMode.Bilinear, InterpolationMode.Default, InterpolationMode.High,
InterpolationMode.HighQualityBicubic, InterpolationMode.HighQualityBilinear, InterpolationMode.Low, InterpolationMode.NearestNeighbor};
SmoothingMode[] smoothingModes = new SmoothingMode[]{SmoothingMode.AntiAlias, SmoothingMode.Default, SmoothingMode.HighQuality, SmoothingMode.HighSpeed,
SmoothingMode.None};
for(int i = 0; i < interpolationModes.Length; i++) {
for(int j = 0; j < smoothingModes.Length; j++) {
Resize(imagePath, width, interpolationModes[i], smoothingModes[j]);
}
}
}
public static void Resize(string imagePath,int width, InterpolationMode interpolationMode, SmoothingMode smoothingMode) {
Image imgPhoto = Image.FromFile(imagePath);
float percent = (float)width / (float)imgPhoto.Width;
int height = (int)(imgPhoto.Height * percent);
Bitmap bmPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = interpolationMode;
grPhoto.SmoothingMode = smoothingMode;
grPhoto.DrawImage(imgPhoto,
new Rectangle(0, 0, width, height),
new Rectangle(0, 0, imgPhoto.Width, imgPhoto.Height ),
GraphicsUnit.Pixel);
grPhoto.Dispose();
string fileName = Path.GetFileName(imagePath);
string path = Path.GetDirectoryName(imagePath)+"\\resized";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
bmPhoto.Save(String.Format("{0}\\{1}_{2}_{3}", path, interpolationMode.ToString(), smoothingMode.ToString(),fileName));
}
源图: 源图http://img110.imageshack.us/img110/4876/sampleaa2.jpg
结果: 结果 http://img110.imageshack.us/img110/2050/resizedsamplesy4.png
PS 我已经尝试过所有现有的 InterpolationMode 和 SmoothingMode 组合。他们都没有给出可接受的结果。