eWo*_*olf 6 c# resize image image-scaling
我正在调整一些图像到用户的屏幕分辨率; 如果宽高比错误,应该剪切图像.我的代码看起来像这样:
protected void ConvertToBitmap(string filename)
{
var origImg = System.Drawing.Image.FromFile(filename);
var widthDivisor = (double)origImg.Width / (double)System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
var heightDivisor = (double)origImg.Height / (double)System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
int newWidth, newHeight;
if (widthDivisor < heightDivisor)
{
newWidth = (int)((double)origImg.Width / widthDivisor);
newHeight = (int)((double)origImg.Height / widthDivisor);
}
else
{
newWidth = (int)((double)origImg.Width / heightDivisor);
newHeight = (int)((double)origImg.Height / heightDivisor);
}
var newImg = origImg.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
newImg.Save(this.GetBitmapPath(filename), System.Drawing.Imaging.ImageFormat.Bmp);
}
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,这很好.但是对于一些图像,结果有一个非常质量较差.它似乎已被调整为非常小(缩略图大小)的东西并再次放大..但图像的分辨率是正确的.我能做什么?
例如原稿图像: 替代文字http://img523.imageshack.us/img523/1430/naturaerowoods.jpg
调整大小的图片示例: alt text http://img523.imageshack.us/img523/2531/naturaerowoods.png
注意:我有一个WPF应用程序,但我使用WinForms函数进行大小调整,因为它更容易,因为我已经需要一个托盘图标的System.Windows.Forms引用.
我目前无法查看.NET源代码,但很可能问题出在该Image.GetThumbnailImage方法中.甚至MSDN都说"当请求的缩略图图像的大小约为120 x 120像素时效果很好,但是你从具有嵌入式缩略图的图像请求一个大的缩略图图像(例如,300 x 300),在缩略图中明显损失质量".要进行真正的大小调整(即不是缩略图),您应该使用该Graphics.DrawImage方法.如果需要,您可能还需要使用它Graphics.InterpolationMode来获得更好的质量.
将方法的最后两行更改为:
var newImg = new Bitmap(newWidth, newHeight);
Graphics g = Graphics.FromImage(newImg);
g.DrawImage(origImg, new Rectangle(0,0,newWidth,newHeight));
newImg.Save(this.GetBitmapPath(filename), System.Drawing.Imaging.ImageFormat.Bmp);
g.Dispose();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6612 次 |
| 最近记录: |