2009-10-26 45 views
6

我碰到過這幾次,並認爲這將是很好的把它放在那裏。什麼是你最好的圖像調整和/或裁剪邏輯。這個想法是,一些方法被稱爲目標圖像,尺寸和裁剪標誌 - 這將返回或保存或任何想要的圖像。最好的調整大小和或​​裁剪邏輯

礦井在下面。從VB轉換到C#所以是的,會有小錯誤,但邏輯是我們正在看的。

// INIT 
// On/off 
bool WeAreCropping = true; 

// Get some dimensions 
int TargetWidth = RequestedWidth; 
int TargetHeight = RequestedHeight; 
int SourceWidth = SourceImage.Width; 
int SourceHeight = SourceImage.Height; 
int ResizeWidth = TargetWidth; 
int ResizeHeight = TargetHeight; 

// GET RESIZE VALUES 
// Are we cropping? 
if (WeAreCropping) { 

    // Get source and target aspect ratio 
    double SourceAspectRatio = SourceWidth/SourceHeight; 
    double TargetAspectRatio = TargetWidth/TargetHeight; 

    // Compare aspect ratios to find out if we should we resize by 
    // width or height or nothing 
    if (TargetAspectRatio < SourceAspectRatio) { 
     ResizeWidth = TargetHeight/SourceHeight * SourceWidth; 
    } 
    else if (TargetAspectRatio > SourceAspectRatio) { 
     ResizeHeight = TargetWidth/SourceWidth * SourceHeight; 
    } 
    else { 
     // Same aspect ratio 
    } 


} 
else { 

    // If the target image is bigger than the source 
    if (TargetWidth > SourceWidth && TargetHeight > SourceHeight) { 
     TargetWidth = SourceWidth; 
     TargetHeight = SourceHeight; 
    } 

    double Ratio = 0; 

    // What ratio should we resize it by 
    if (SourceWidth/TargetWidth > SourceHeight/TargetHeight) { 
     Ratio = SourceWidth/TargetWidth; 
    } 
    else { 
     Ratio = SourceHeight/TargetHeight; 
    } 

    ResizeWidth = Math.Ceiling(SourceWidth/Ratio); 

    ResizeHeight = Math.Ceiling(SourceHeight/Ratio); 
} 

// TIME TO DO SUMFINK 
// Resize the image using ResizeWidth and ResizeHeight 
// Do it 

if (WeAreCropping) { 
    // Crop the resized image at the center TargetWidth and TargetHeight 
    // Do it 
} 

我懷疑這可能會更優雅,所以也許你可以做得更好。

回答

4

我想說你應該使用標準幾何類型,如RectangleSize。那麼你應該也可以支持一個用例,當調用者想要將圖像放在一個更大的矩形中時,但仍然想保持原始圖像大小的比例。

執行調整大小的一種方法可以找到here

+0

感謝您的鏈接。 – Maleks 2009-11-01 16:55:01

+9

有一個「謝謝」的特殊按鈕:)) – 2009-11-01 23:13:44

+0

鏈接被破壞 – Flexicoder 2016-01-18 16:15:59

0

這可能比你所需要的要多一點,但是對於一些高級裁剪技術的例子,check this out

+0

該鏈接給我一個500錯誤。 – 2013-02-17 20:49:00