2012-02-15 2 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

+0

если 'objGraphic.Width> intWidth',' intWidth/objGraphic .Width' всегда будет <1. То же самое с высотой. И поскольку мы выполняем 'Min (1, [некоторое число меньше или равно 1])', оно будет меньше или равно 1. – Rodaine

+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