What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleSplit an image into smaller image files in Visual Basic 6
DescriptionThis example shows how to split an image into smaller image files in Visual Basic 6.
Keywordsimage processing, graphics, split image, bitmap, split bitmap, save image, example, example program, Windows Forms programming, Visual Basic 6, VB 6

Recently I needed separate bitmap files for the icons in the Visual Studio toolbox. I took a screen shot and then, rather than splitting the icons apart manually, I wrote this program to do it. The following code does all of the work.

' Split the file.
Private Sub cmdGo_Click()
Dim wid As Integer
Dim hgt As Integer
Dim piece_name As String
Dim num_rows As Integer
Dim num_cols As Integer
Dim row As Integer
Dim col As Integer
Dim X As Integer
Dim Y As Integer
Dim filename As String

    ' Get the inputs.
    wid = Val(txtWidth.Text)
    hgt = Val(txtHeight.Text)
    picWhole.Picture = LoadPicture(txtFile.Text)

    ' Start splitting the Bitmap.
    piece_name = txtFile.Text
    piece_name = Left$(piece_name, InStrRev(piece_name, _
    picPiece.Width = wid
    picPiece.Height = hgt

    num_rows = CInt(picWhole.ScaleHeight / hgt)
    num_cols = CInt(picWhole.ScaleWidth / wid)
    Y = 0
    For row = 0 To num_rows - 1
        X = 0
        For col = 0 To num_cols - 1
            ' Copy the piece of the image.
            picPiece.PaintPicture picWhole.Picture, 0, 0, _
                wid, hgt, X, Y, wid, hgt

            ' Save the piece.
            filename = piece_name & _
                Format$(row, "00") & _
                Format$(col, "00") & ".bmp"
            SavePicture picPiece.Image, filename

            ' Move to the next column.
            X = X + wid
        Next col
        Y = Y + hgt
    Next row
    MsgBox "Created " & num_rows * num_cols & " files", _
        vbOKOnly, "Done"
End Sub
The code gets the width and height that the smaller pieces should have and loads the original image. It sizes the picPiece PictureBox control so it can draw the pieces on it.

Next the code figures out how many rows and columns of smaller images will fit completely within the original image and loops through the rows and columns.

For each row/column value, the code uses PaintPicture to copy the appropriate piece to the picPiece PictureBox and saves the result in a bitmap file.

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