我正在开发一个应用程序来处理在宽幅图像扫描仪上扫描的图像。这些图片在ImageBrush
上显示为Canvas
。
在这个Canvas
上,他们可以用鼠标做Rectangle
来定义要裁剪的区域。
我的问题是根据原始图片大小调整Rectangle
的大小,以便裁剪原始图片上的确切区域。
到目前为止,我已经尝试了很多东西,它只是让我的大脑变得平坦,找出正确的解决方案。
我知道我需要得到原始图像比画布上显示的图像大的百分比。
原始图像的尺寸为:
h:5606
w:7677
当我显示图像时,它们是:
h:1058,04
w:1910
这给出了这些数字:
float percentWidth = ((originalWidth - resizedWidth) / originalWidth) * 100;
float percentHeight = ((originalHeight - resizedHeight) / originalHeight) * 100;
percentWidth = 75,12049
percentHeight = 81,12665
从这里我无法想象如何正确调整Rectangle
的大小,以适应原始图像。
我的最后一种方法是:
int newRectWidth = (int)((originalWidth * percentWidth) / 100);
int newRectHeight = (int)((originalHeight * percentHeight) / 100);
int newRectX = (int)(rectX + ((rectX * percentWidth) / 100));
int newRectY = (int)(rectY + ((rectY * percentHeight) / 100));
希望有人可以引导我朝着正确的方向前进,因为我在这里偏离轨道,我看不到我所缺少的东西。
解决方案
private System.Drawing.Rectangle FitRectangleToOriginal(
float resizedWidth,
float resizedHeight,
float originalWidth,
float originalHeight,
float rectWidth,
float rectHeight,
double rectX,
double rectY)
{
// Calculate the ratio between original and resized image
float ratioWidth = originalWidth / resizedWidth;
float ratioHeight = originalHeight / resizedHeight;
// create a new rectagle, by resizing the old values
// by the ratio calculated above
int newRectWidth = (int)(rectWidth * ratioWidth);
int newRectHeight = (int)(rectHeight * ratioHeight);
int newRectX = (int)(rectX * ratioWidth);
int newRectY = (int)(rectY * ratioHeight);
return new System.Drawing.Rectangle(newRectX, newRectY, newRectWidth, newRectHeight);
}
答案 0 :(得分:2)
我认为唯一可靠的选择是让用户放大图像(100%或更高的缩放级别)并对图像的一部分进行选择。通过这种方式,他们可以进行精确的基于像素的选择。 (假设选择矩形的目的是选择图像的一部分。)
现在您的问题是您正在使用浮点计算,因为75%的缩放级别和舍入错误会使您的选择矩形不准确。无论你做什么,当你试图在缩小的图像上做出选择时,你都没有选择精确的像素 - 你在调整矩形大小时选择了部分像素。由于无法选择部分像素,因此选择边将向上或向下舍入,因此您可以在给定方向上选择一个像素太多或一个像素太少。
我刚才注意到的另一个问题是你扭曲了你的形象 - 横向是75%变焦,垂直是81%。这使得用户更加困难,因为图像将在两个方向上以不同方式平滑。水平4个原始像素将在3个输出像素上插值;垂直5个原始像素将在4个输出像素上插值。
答案 1 :(得分:1)
你实际上在做一种投射形式。不要使用百分比,只需使用5606和1058,4 = ~5.30之间的比例。当用户拖动矩形时,重新投影它是selectedWidth * 5606/1058.4
。