Click here to Skip to main content
13,357,438 members (69,326 online)
Click here to Skip to main content
Add your own
alternative version


27 bookmarked
Posted 3 Aug 2009

Smart PictureBox Control

, 7 Aug 2009
Rate this:
Please Sign up or sign in to vote.
A custom picturebox control that can load, save, and edit an image through a popup menu.


The PictureBox control is one of the most popular controls to display and receive an image from a user. However, most of the time, you’ll find yourself writing repetitive tasks such as:

  • Loading an image from file
  • Saving an image from a control onto a file
  • Handling edit operations such as Copy, Cut, Paste, Delete, Undo, etc.

The SmartPictureBox control puts all this together through a context menu as shown below:

Using the code

The SmartPictureBox control extends the PictureBox control by adding a context menu and a couple of methods and properties to load, save, and edit an image.

<ToolboxBitmap(GetType(PictureBox))> Public Class SmartPictureBox : Inherits PictureBox

#Region " Fields "
Friend WithEvents cmsPhotoDelete As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents cmsPhotoPaste As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents cmsPhotoCopy As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents cmsPhotoCut As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents ToolStripSeparator1 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents cmsPhotoLoad As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents cmsPhotoSave As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents cmsPhotoUndo As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents cmsPhoto As System.Windows.Forms.ContextMenuStrip


The LoadImage method browses for an image that it loads into the control. The image should be equal to or below the set file size limit.

Private Sub LoadImage(ByVal sourceControl As Control, ByVal fileSizeLimit As Long)

    Dim openFileDLG As New OpenFileDialog()

        Cursor.Current = Cursors.WaitCursor()

        With openFileDLG
                .InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyPictures
            Catch ex As Exception
                Exit Try
            End Try

            .Filter = "JPG (*.jpg)|*.jpg|JPEG (*.jpeg)|*.jpeg|Bitmap (*.bmp) |*.bmp|" & _
                      "GIF (*.gif) |*.gif|PNG (*.png) |*.png"
        End With

        If openFileDLG.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim data() As Byte = ReadBytes(openFileDLG.FileName.ToString())
            If fileSizeLimit > 0 AndAlso data.LongLength > fileSizeLimit Then
                Throw New ArgumentException("Image is bigger than allowed maximum size!")
                Dim ms As New MemoryStream(CType(data, Byte()))
                If TypeOf sourceControl Is PictureBox Then
                    CType(sourceControl, PictureBox).Image = Image.FromStream(ms)
                End If
            End If
        End If

    Catch eX As Exception

        Cursor.Current = Cursors.Default()

    End Try

End Sub

ReadBytes, an overloaded method, returns the bytes of a file from the supplied path or image.

Private Function ReadBytes(ByVal path As String) As Byte()

        'A stream of bytes that represnts the binary file
        Dim fs As FileStream = New FileStream(path, FileMode.Open, FileAccess.Read)

        'The reader reads the binary data from the file stream
        Dim reader As BinaryReader = New BinaryReader(fs)

        'Bytes from the binary reader stored in data array
        Dim data() As Byte = reader.ReadBytes(CInt(fs.Length))


        Return data

    Catch ex As Exception
        Throw ex

    End Try

End Function

Private Function ReadBytes(ByVal data As Image) As Byte()


        Dim ms As New IO.MemoryStream()
        data.Save(ms, Imaging.ImageFormat.Jpeg)
        Return ms.ToArray()

    Catch ex As Exception
        Throw ex

    End Try

End Function

The SaveImage method opens a save file dialog to save the supplied image with the supplied file name:

Private Sub SaveImage(ByVal data As Image, ByVal fileName As String)

    Dim saveFileDLG As New SaveFileDialog()


        Cursor.Current = Cursors.WaitCursor()

        With saveFileDLG

                .InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyPictures
            Catch ex As Exception
                Exit Try
            End Try

            .Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif|PNG (*.png) |*.png"
            .Title = "Save image to a file"
            .FileName = fileName

        End With

        If Not String.IsNullOrEmpty(saveFileDLG.FileName) Then

            ' Saves the Image via a FileStream created by the OpenFile method.
            Dim fs As FileStream = CType(saveFileDLG.OpenFile(), FileStream)

            ' Saves the Image in the appropriate ImageFormat based upon the
            ' file type selected in the dialog box.
            ' NOTE that the FilterIndex property is one-based.
            Select Case saveFileDLG.FilterIndex

                Case 1 : data.Save(fs, ImageFormat.Jpeg)
                Case 2 : data.Save(fs, ImageFormat.Bmp)
                Case 3 : data.Save(fs, ImageFormat.Gif)
                Case 4 : data.Save(fs, ImageFormat.Png)

            End Select


        End If

    Catch eX As Exception

        Cursor.Current = Cursors.Default()

    End Try

End Sub


  • ReadOnly: If set to True, the pop up menu of the control will be hidden.
  • ImageSizeLimit: This property sets or gets the maximum image file size limit.

Other feature(s) include

  • Enabling and disabling the menu appropriately depending upon what’s on the Clipboard etc.

You can include the SmartPictureBox.vb file in your Visual Basic Windows Forms application, and this control will automatically appear on the toolbox, which you can drag and drop onto the form.

To use it in C#, create a class library, compile it, right click the Toolbox, choose items, navigate to the DLL, and the control will automatically be added onto your toolbox, which you can then drag and drop onto a Windows form.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior) Joint Clinical Research Centre
Uganda Uganda
Wilson Kutegeka, a Microsoft MVP has wide knowledge in analyzing, designing, developing, implementing and supporting corporate software that follow an object oriented methodology and has developed computer software in more than six computer programming languages and technologies. Currently, he has put his focus on Visual Basic, C#, T-SQL, MS SQL Server among others.

MVP Profile:

You may also be interested in...


Comments and Discussions

GeneralAn interesting article Pin
rctaubert10-Aug-09 10:36
memberrctaubert10-Aug-09 10:36 
Interesting article and control.

One question; does your control preserve all metadata that might be attached to the image and is it lossless????

Thank you
GeneralRe: An interesting article Pin
Kutegz11-Aug-09 0:43
memberKutegz11-Aug-09 0:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180111.1 | Last Updated 7 Aug 2009
Article Copyright 2009 by Kutegz
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid