Tuesday, April 6, 2010

how to get optimum sizes of resized image with proportion in .NET


Private _MaxWidth As Integer
Private _MaxHeight As Integer

Public Property MaxWidth() As Integer
Get
Return _MaxWidth
End Get
Set(ByVal value As Integer)
_MaxWidth = value
End Set
End Property

Public Property MaxHeight() As Integer
Get
Return _MaxHeight
End Get
Set(ByVal value As Integer)
_MaxHeight = value
End Set
End Property



Private Function CalculateOptimumImageSize(ByVal src As System.Drawing.Image) As Integer()
Dim sizeImgDim As Integer() = New Integer(1) {}

sizeImgDim(0) = src.Width
sizeImgDim(1) = src.Height

'if the max and min are larger than the original size, therefore follow the original
If sizeImgDim(0) > _MaxWidth OrElse sizeImgDim(1) > _MaxHeight Then
Dim imageRatio As Decimal = CDec(sizeImgDim(0)) / CDec(sizeImgDim(1))
Dim w As Decimal = imageRatio * CDec(_MaxHeight)
If w > _MaxWidth Then

sizeImgDim(0) = _MaxWidth
Else
sizeImgDim(0) = Convert.ToInt32(w)
End If


Dim h As Decimal = CDec(_MaxWidth) / imageRatio
If h > _MaxHeight Then

sizeImgDim(1) = _MaxHeight
Else

sizeImgDim(1) = Convert.ToInt32(h)

End If
End If
Return sizeImgDim
End Function