What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleCopy part of an image into a new PictureBox in Visual Basic .NET
DescriptionThis example shows how to copy part of an image into a new PictureBox in Visual Basic .NET.
Keywordsgraphics, image processing, copy image, DrawImage, Visual Basic .NET, VB.NET

When you enter top, left, width, and height values and click the Copy button, the program uses the following code to copy part of the image on the left and display it on the right.

' Copy part of the original image.
Private Sub btnCopy_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnCopy.Click
    Dim top As Integer = Integer.Parse(txtTop.Text)
    Dim left As Integer = Integer.Parse(txtLeft.Text)
    Dim width As Integer = Integer.Parse(txtWidth.Text)
    Dim height As Integer = Integer.Parse(txtHeight.Text)

    ' Make a Bitmap to hold the result.
    Dim bm As New Bitmap(width, height)

    ' Associate a Graphics object with the Bitmap
    Using gr As Graphics = Graphics.FromImage(bm)
        ' Define source and destination rectangles.
        Dim src_rect As New Rectangle(left, top, width, _
        Dim dst_rect As New Rectangle(0, 0, width, height)

        ' Copy that part of the image.
        gr.DrawImage(picOriginal.Image, dst_rect, src_rect, _
    End Using

    ' Display the result.
    picResult.Image = bm
End Sub
This code starts by getting the values you entered and making a Bitmap to hold the result. It then makes a Graphics object associated with the Bitmap.

It defines a source Rectangle to indicate the part of the original image that should be copied and a destination Rectangle to indicate where that part of the image should be drawn in the new Bitmap. It then calls the Graphics object's DrawImage method to copy that part of the image.

The code finishes by displaying the new Bitmap in the PictureBox named pixResult.

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