Related Question如何將縮放圖像上的XY座標和高度/寬度轉換爲原始大小的圖像?
我想做的事情,在鏈接的問題,但用C#。我正在顯示縮放的圖像,並允許用戶選擇要裁剪的區域。但是,我不能只從縮放的圖像選擇中獲取x1y1,x2y2座標,並從原始圖像中裁剪。我試過在另一個問題上做一些基本的數學運算,但這顯然不是正確的方法(它絕對更接近)。
編輯
初始圖像尺寸:w = 1024 h = 768
縮放圖像尺寸:w = 550 h = 412
我開始用圖像,說1024×768。我希望它在550x550盒子中儘可能大。我使用以下方法獲取縮放後的圖像大小(同時保持寬高比)。然後,我會對這些新維度進行基本調整。
至於選區,它可以是任何東西(0,0)到(100,100)。
private static Rectangle MaintainAspectRatio(Image imgPhoto, Rectangle thumbRect)
{
int sourceWidth = imgPhoto.Width; int sourceHeight = imgPhoto.Height; int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)thumbRect.Width/(float)sourceWidth);
nPercentH = ((float)thumbRect.Height/(float)sourceHeight);
//if we have to pad the height pad both the top and the bottom
//with the difference between the scaled height and the desired height
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = (int)((thumbRect.Width - (sourceWidth * nPercent))/2);
}
else
{
nPercent = nPercentW;
destY = (int)((thumbRect.Height - (sourceHeight * nPercent))/2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Rectangle retRect = new Rectangle(thumbRect.X, thumbRect.Y, destWidth, destHeight);
return retRect;
}
其中是縮放圖像的零點?在左上方還是左下方? – 2011-02-14 16:43:11
我假設左上角 – scottm 2011-02-14 16:43:46
您使用變換(2x2矩陣)縮放圖像。用該矩陣的逆來執行座標轉換。請提供具體的原始圖像大小,位置以及變換後的圖像大小,位置的數字示例 - 這使得有些人可以更容易地這樣思考,並且消除了一些不明確之處。 – 2011-02-14 16:44:08