问题描述
作为Size
,Width
和Height
是System.Drawing 的
;Get()
属性.图片
如何在 C# 中在运行时调整 Image 对象的大小?
As Size
, Width
and Height
are Get()
properties of System.Drawing.Image
;
How can I resize an Image object at run-time in C#?
现在,我正在创建一个新的 Image
使用:
Right now, I am just creating a new Image
using:
// objImage is the original Image
Bitmap objBitmap = new Bitmap(objImage, new Size(227, 171));
推荐答案
这将执行高质量的调整大小:
This will perform a high quality resize:
/// <summary>
/// Resize the image to the specified width and height.
/// </summary>
/// <param name="image">The image to resize.</param>
/// <param name="width">The width to resize to.</param>
/// <param name="height">The height to resize to.</param>
/// <returns>The resized image.</returns>
public static Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width,image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
wrapMode.SetWrapMode(WrapMode).TileFlipXY)
防止图像边界周围出现重影——简单的调整大小会采样超出图像边界的透明像素,但通过镜像我们可以获得更好的样本(这个设置非常明显)destImage.SetResolution
不论物理尺寸如何都保持 DPI -- 在缩小图像尺寸或打印时可能会提高质量
合成控制像素与背景的混合方式 -- 可能不需要,因为我们只绘制一件事.
graphics.CompositingMode
确定来自源图像的像素是覆盖还是与背景像素组合.SourceCopy
指定在呈现颜色时,它会覆盖背景颜色.graphics.CompositingQuality
决定了分层图像的渲染质量级别.
保持纵横比留给读者作为练习(实际上,我只是不认为这个功能的工作是为你做这件事).
Maintaining aspect ratio is left as an exercise for the reader (actually, I just don't think it's this function's job to do that for you).
此外,这是一篇很好的文章,描述了一些调整图像大小的陷阱.上面的函数会覆盖大部分,但是你还是要担心保存.
Also, this is a good article describing some of the pitfalls with image resizing. The above function will cover most of them, but you still have to worry about saving.
这篇关于如何调整图像的大小 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!