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

时间:2010-09-07 14:04:24

标签: c# asp.net image-processing image-manipulation

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

例如,宽度为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;
        }

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

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

由于原始图片小于大小增加值,我不想“逐渐增加”,而是保持相同的大小。我想要的效果是绘制一个大小为2000x2000的矩形,并在其中心绘制图像。

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

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

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

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

提前致谢。

1 个答案:

答案 0 :(得分:1)

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

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