当原始图像高度和宽度小于缩放高度和宽度时,图像缩放不起作用

我在尝试缩放图像时遇到了问题。 当我试图缩放(原始)的图像小于我想要扩展到的尺寸时,问题出现了。

例如,宽度为850像素,高度为700像素的图像试图将其放大到950像素宽度和高度。 图像似乎正确缩放,但在我的位图上绘制错误。 随后将展开缩放图像的代码。 发送到ScaleToFitInside的宽度是试图缩放到的宽度和高度,在我的例子中都是950px。

public static Image ScaleToFitInside(Image image, int width, int height) { Image reszied = ScaleToFit(image, width, height); Bitmap bitmap = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(bitmap)) { g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; Rectangle rect = new Rectangle(0, 0, width, height); g.FillRectangle(Brushes.White, rect); int x = (int)(((float)width - (float)reszied.Width) / 2); int y = (int)(((float)height - (float)reszied.Height) / 2); Point p = new Point(x, y); g.DrawImageUnscaled(reszied, p); foreach (PropertyItem item in image.PropertyItems) { bitmap.SetPropertyItem(item); } } return bitmap; } public static Image ScaleToFit(Image image, int maxWidth, int maxHeight) { int width = image.Width; int height = image.Height; float scale = Math.Min( ((float)maxWidth / (float)width), ((float)maxHeight / (float)height)); return (scale < 1) ? Resize(image, (int)(width * scale), (int)(height * scale)) : image; } public static Image Resize(Image image, int width, int height) { Bitmap bitmap = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(bitmap)) { g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; Rectangle rect = new Rectangle(0, 0, width, height); g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel); foreach (PropertyItem item in image.PropertyItems) { bitmap.SetPropertyItem(item); } } return bitmap; } 

因此,图片会缩放,但是我的位图上出现了错误,导致图像“掉落”在我的位图之外,而不是呈现整个自身。

示例:发送值2000×2000(尝试升级)时。 发生以下情况。

由于原始图片小于升尺寸值,我不想“扫描它”,而是保持相同的尺寸。 我想要的效果是绘制一个大小为2000×2000的矩形,并在其中心绘制图像。

我的示例图片产生了以下值:

width = 2000; 身高= 2000; resized.Width将为1000并resize。高度为737(原始图片大小)。

x =(2000-1000)/ 2 = 500; y =(2000 – 737)/ 2 = 631。

将这些值绘制到纸张上并将其与矩形相匹配时,它似乎是正确的值,但图像仍然在错误的位置绘制,而不是在中间绘制。

提前致谢。

当你’升级’时你会发现以下2个变量是否定的?

 int x = (int)(((float)width - (float)reszied.Width) / 2); int y = (int)(((float)height - (float)reszied.Height) / 2);