Results 1 to 5 of 5

Thread: VB.Net - Simple Proper Image Scaling in Correct Aspect Ratio

Threaded View

  1. #1

    Thread Starter
    Hyperactive Member stepdragon's Avatar
    Join Date
    Aug 2011
    Location
    Cincinnati
    Posts
    288

    VB.Net - Simple Proper Image Scaling in Correct Aspect Ratio

    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:
    1. Public Function ScaleImage(ByVal OldImage As Image, ByVal TargetHeight As Integer,_
    2.                            ByVal TargetWidth As Integer) As System.Drawing.Image
    3.  
    4.         Dim NewHeight As Integer = TargetHeight
    5.         Dim NewWidth As Integer = NewHeight / OldImage.Height * OldImage.Width
    6.  
    7.         If NewWidth > TargetWidth Then
    8.             NewWidth = TargetWidth
    9.             NewHeight = NewWidth / OldImage.Width * OldImage.Height
    10.         End If
    11.  
    12.         Return New Bitmap(OldImage, NewWidth, NewHeight)
    13.  
    14. End Function

    Example Usage:

    VB.Net Code:
    1. Picturebox1.Image = ScaleImage(Image.Fromfile(Picture.png),_
    2.                                Picturebox1.Height, Picturebox1.Width)

    Note: Set the Picturebox's SizeMode to CenterImage
    Last edited by stepdragon; Oct 1st, 2011 at 05:49 PM. Reason: Great Suggestion by BB

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width