This function will do the job:
Code:
Private Function SizeLimitedImage(image As Image, maxPixels As Integer) As Image
If image.Width * image.Height > maxPixels Then
Dim aspectRatio As Double = image.Height / image.Width
Dim targetHeight As Integer = CInt(Math.Sqrt(aspectRatio * maxPixels))
Dim targetWidth As Integer = CInt(maxPixels / targetHeight)
Return New Bitmap(image, targetWidth, targetHeight)
Else
Return image
End If
End Function
The logic of this is that you want the image to keep the same shape, so if w is the target width and h is the target height:
Code:
h/w = aspect ratio (= image height / image width)
w*h = maximum number of pixels
Multiplying the two equations to eliminate w we get:
Code:
h^2 = aspect ratio * maximum number of pixels
hence the square root.
BB