从缩放的小尺寸图像获得相同的矩形位置

时间:2017-12-08 07:53:04

标签: c# math geometry gdi+ system.drawing

我正在尝试处理一个大尺寸的图像。由于处理需要花费太多时间才能完成,我在处理之前调整图像大小。处理后我在小尺寸图像上绘制一个矩形。我怎么能翻译该矩形与原始未缩放图像的坐标即:在未缩放图像上的相同位置绘制矩形。

我正在使用以下代码调整图片大小

public static Size ResizeKeepAspect(Size CurrentDimensions, int maxWidth, int maxHeight)
{
    int newHeight = CurrentDimensions.Height;
    int newWidth = CurrentDimensions.Width;
    if (maxWidth > 0 && newWidth > maxWidth) //WidthResize
    {
        Decimal divider = Math.Abs((Decimal)newWidth / (Decimal)maxWidth);
        newWidth = maxWidth;
        newHeight = (int)Math.Round((Decimal)(newHeight / divider));
    }
    if (maxHeight > 0 && newHeight > maxHeight) //HeightResize
    {
        Decimal divider = Math.Abs((Decimal)newHeight / (Decimal)maxHeight);
        newHeight = maxHeight;
        newWidth = (int)Math.Round((Decimal)(newWidth / divider));
    }
    return new Size(newWidth, newHeight);
}

这就是我想要实现的目标

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

Rectangle ConvertToLargeRect(Rectangle smallRect, Size largeImageSize, Size smallImageSize)
{
    double xScale = (double)largeImageSize.Width / smallImageSize.Width;
    double yScale = (double)largeImageSize.Height / smallImageSize.Height;    
    int x = (int)(smallRect.X * xScale + 0.5);
    int y = (int)(smallRect.Y * yScale + 0.5);
    int right = (int)(smallRect.Right * xScale + 0.5);
    int bottom = (int)(smallRect.Bottom * yScale + 0.5);
    return new Rectangle(x, y, right - x, bottom - y);
}

答案 1 :(得分:0)

这是一个简单的关系计算。例如:

Image A 100 (w) x 100 (h): Pixel x = 10, y = 30
Image B 200 (w) x 200 (h): Pixel x = a, y = b

10 / 100 (w) = a / 200 (w) 
200 (w) * 10 / 100 (w) = a 
a = 20

30 / 100 (h) = b / 200 (h) 
200 (h) * 30 / 100 (h) = b 
a = 60