2012-02-15 47 views
0

如何爲圖片大小調整代碼添加約束?我希望圖像不會超過165x146。下面的代碼不保留約束當圖像是525x610如何向圖片大小調整代碼添加約束?即不大於165x146

 intWidth = 165 '*** Fix Width ***' 
     intHeight = 146 '*** Fix Width ***' 

      If objGraphic.Width > intWidth Then 
       Dim ratio As Double = objGraphic.Height/objGraphic.Width 
       intHeight = ratio * intWidth 
       objBitmap = New Bitmap(objGraphic, intWidth, intHeight) 
      ElseIf objGraphic.Height > intHeight Then 
       Dim ratio As Double = objGraphic.Width/objGraphic.Height 
       intWidth = ratio * intHeight 
       objBitmap = New Bitmap(objGraphic, intWidth, intHeight) 
      Else 
       objBitmap = New Bitmap(objGraphic) 
      End If 

回答

1

我認爲你想保持圖像的縱橫比?如果是這樣,這種方法可能是適當的;您需要按照您獲得的比例乘以寬度和高度。

'define max size of image 
intWidth = 165 
intHeight = 146 

'if the width/height is larger than the max, determine the appropriate ratio 
Dim widthRatio as Double = Math.Min(1, intWidth/objGraphic.Width) 
Dim heightRatio as Double = Math.Min(1, intHeight/objGraphic.Height) 

'take the smaller of the two ratios as the one we will use to resize the image 
Dim ratio as Double = Math.Min(widthRatio, heightRatio) 

'apply the ratio to both the width and the height to ensure the aspect is maintained 
objBitmap = New Bitmap(objGraphic, CInt(objGraphic.Width * ratio), CInt(objGraphic.Height * ratio)) 

編輯:可能需要新的高度和寬度顯式轉換爲整數

+0

,將返回525x610,因爲比爲1 – Bruno 2012-02-15 20:30:52

+0

如果'objGraphic.Width> intWidth','intWidth/objGraphic .Width'將始終爲<1。與高度相同。因爲我們執行'Min(1,[某個數小於或等於1]),所以它將小於或等於1. – Rodaine 2012-02-15 21:28:01

+0

在你的例子中,'widthRatio = MIN(1,0.314)= 0.314', 'heightRatio = MIN(1,0.239)= 0.239',並且'ratio = MIN(0.314,0.239)= 0.239'。你的新寬度將是'525 * .239 = 125',你的高度是'610 * .239 = 146' – Rodaine 2012-02-15 21:33:06