First Submission to the CodeBank!
While I was working on a program I found the need to display pictures, and (since I'm OCD) I needed them to be the correct aspect ratio. This sounds (and is) quite simple, but sometimes things get over complicated. It actually took me a few tries to figure this out, but what I ended up with was a Very Simple, Extremely Portable Function which can scale any System.Drawing.Image to any Target Size.
While I was working on it, I did multiple searches for simmilar code, but what I found was usually WAY over complicated, or only scaled down. I'm Submitting this after searching the CodeBank and not finding anything resembling a scaling snippet. I'm hoping other people can benefit from the simplicity of this.
Forgive me for not commenting, I believe it too simple to require comments (they just get in the way without saying anything about it).
Modified by Suggestion of boops boops. Credit where due.
VB.Net Code:
Public Function ScaleImage(ByVal OldImage As Image, ByVal TargetHeight As Integer,_ ByVal TargetWidth As Integer) As System.Drawing.Image Dim NewHeight As Integer = TargetHeight Dim NewWidth As Integer = NewHeight / OldImage.Height * OldImage.Width If NewWidth > TargetWidth Then NewWidth = TargetWidth NewHeight = NewWidth / OldImage.Width * OldImage.Height End If Return New Bitmap(OldImage, NewWidth, NewHeight) End Function
Example Usage:
VB.Net Code:
Picturebox1.Image = ScaleImage(Image.Fromfile(Picture.png),_ Picturebox1.Height, Picturebox1.Width)
Note: Set the Picturebox's SizeMode to CenterImage




Reply With Quote
