Dan*_*eny 1 .net c# image image-processing
我正在尝试调整图像大小.我认为这是一项简单的任务......
这是我的代码(注意,这两个Save调用仅用于调试以说明问题):
var newSize = new Size { Width = 450, Height = 250 };
using (var img = (Bitmap)Image.FromFile(sourceImageFilename))
{
var outputImage = new Bitmap(newSize.Width, newSize.Height);
// Save input image for debugging (screenshot below)
img.Save(@"M:\Coding\Photos\Temp\input.jpg");
using (Graphics gr = Graphics.FromImage(img))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(outputImage, new Rectangle(0, 0, newSize.Width, newSize.Height));
}
// Save output image for debugging (screenshot below)
outputImage.Save(@"M:\Coding\Photos\Temp\output.jpg");
}
Run Code Online (Sandbox Code Playgroud)
这似乎是很多人使用的完全相同的代码(在许多答案中存在于SO中).但是,这是写入磁盘的两个图像的样子:
原始图像为5344x3006,newSize(黑色输出图像)为450x250.
我的所有其他代码都工作正常(使用SetPixel读取输入图像中的像素等),只是这个调整大小已经坏了.使用Bitmap构造函数进行调整大小很好(但是调整质量很差).
您需要从OutputImage获取图形.
public static Bitmap Scale(this Bitmap inputImage, Size newSize)
{
var outputImage = new Bitmap(newSize.Width, newSize.Height);
inputImage.Save(@"M:\Coding\Photos\Temp\input.jpg");
using (Graphics gr = Graphics.FromImage(outputImage))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(inputImage, new Rectangle(0, 0, newSize.Width, newSize.Height));
}
outputImage.Save(@"M:\Coding\Photos\Temp\output.jpg");
return outputImage;
}
Run Code Online (Sandbox Code Playgroud)