What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleResize an image in VB .NET
Keywordsresize, image, VB.NET, graphics
CategoriesGraphics, VB.NET
The Graphics object's DrawImage method copies an image much as Visual Basic 6's PaintPicture method does. In VB .NET, however, there are 30 overloaded versions of this routine. One of them takes as parameters the source bitmap and destination position for the copied image.

The program makes a new Bitmap object of the desired final size. It then uses that object's DrawImage routine to copy the source image into the entire destination image. It then assigns the result to a PictureBox's Image property to display the result.

Private Sub btnScale_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnScale.Click
    ' Get the scale factor.
    Dim scale_factor As Single = Single.Parse(txtScale.Text)

    ' Get the source bitmap.
    Dim bm_source As New Bitmap(picSource.Image)

    ' Make a bitmap for the result.
    Dim bm_dest As New Bitmap( _
        CInt(bm_source.Width * scale_factor), _
        CInt(bm_source.Height * scale_factor))

    ' Make a Graphics object for the result Bitmap.
    Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)

    ' Copy the source image into the destination bitmap.
    gr_dest.DrawImage(bm_source, 0, 0, _
        bm_dest.Width + 1, _
        bm_dest.Height + 1)

    ' Display the result.
    picDest.Image = bm_dest
End Sub
In this example, picDest has SizeMode = AutoSize so the control automatically resizes to fit the image.

Note also that DrawImage uses anti-aliasing to smooth the result. In other words, if you enlarge the image it smoothes things out so you don't see big blocky pixels. The result isn't perfect but it's not bad and DrawImage is very fast.

Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.