将图像调整为更小只是切断边缘
Posted
技术标签:
【中文标题】将图像调整为更小只是切断边缘【英文标题】:Resizing an Image smaller just cuts off the edge instead 【发布时间】:2012-06-16 21:41:05 【问题描述】:这一切都在 C# 中:
我正在使用此代码调整图像大小:
_image = (Image)new Bitmap(_refImage, _width, _height);
_refImage 只是一个参考图像,与原始图像相同,因此如果我多次调整大小,分辨率不会混乱。
如果我将图像放大,此代码可以正常工作,它会按预期拉伸它。
但是,如果我将图像缩小,那么它只会切断边缘。
我只是调整宽度,因为我只想改变宽度。
【问题讨论】:
this 会工作吗? 不,它仍然给出相同的结果。 【参考方案1】:我找到了一个可能有效的链接:Here。希望对您有所帮助。
【讨论】:
是的!谢谢,工作得非常好。我需要使用 Image.GetThumbNailImage 并且它有效。【参考方案2】:试试这个:
/// <summary>
/// Scales to within given boundaries - Aspect ratio is kept. High Quality Bi-Cubic interpolation is used.
/// If boundary is larger than the image, then image is scaled up; if smaller, it is scaled down.
/// </summary>
/// <param name="originalImg">Image: Image to scale</param>
/// <param name="width">Int: Restriction on width for output size. Must be greater than zero</param>
/// <param name="height">Int: Restriction on height for output size. Must be greater than zero</param>
/// <param name="backgroundColour">Color: Colour to shade background behind image</param>
/// <returns>Image: Scaled Image</returns>
/// <exception cref="ArgumentException">[ArgumentException] Boundary dimensions must exceed zero</exception>
public static Image ScaleToFit(Image originalImg, int width, int height, Color backgroundColour)
if (originalImg == null) return null;
if (width < 1 || height < 1) throw new ArgumentException("ScaleToFit: Boundary dimensions must exceed zero.");
var destX = 0;
var destY = 0;
float nPercent;
var nPercentW = (width / (float)originalImg.Width);
var nPercentH = (height / (float)originalImg.Height);
if (nPercentH < nPercentW)
nPercent = nPercentH;
destX = Convert.ToInt16((width - (originalImg.Width * nPercent)) / 2);
else
nPercent = nPercentW;
destY = Convert.ToInt16((height - (originalImg.Height * nPercent)) / 2);
var destWidth = (int)(originalImg.Width * nPercent);
var destHeight = (int)(originalImg.Height * nPercent);
var bmPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(originalImg.HorizontalResolution, originalImg.VerticalResolution);
var grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(backgroundColour);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(originalImg,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(0, 0, originalImg.Width, originalImg.Height),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
注意:这会保持纵横比,如果您想足够容易地倾斜,可以更改它。
【讨论】:
以上是关于将图像调整为更小只是切断边缘的主要内容,如果未能解决你的问题,请参考以下文章