Click here to Skip to main content
15,878,852 members
Articles / Programming Languages / Visual Basic

Smart PictureBox Control

Rate me:
Please Sign up or sign in to vote.
4.47/5 (8 votes)
7 Aug 2009CPOL1 min read 36.3K   1.7K   27   2
A custom picturebox control that can load, save, and edit an image through a popup menu.

Introduction

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.

VB
<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.

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

    Dim openFileDLG As New OpenFileDialog()

    Try
        Cursor.Current = Cursors.WaitCursor()

        With openFileDLG
            Try
                .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!")
            Else
                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
        MessageBox.Show(eX.Message)

    Finally
        Cursor.Current = Cursors.Default()

    End Try

End Sub

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

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

        '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))

        fs.Close()
        reader.Close()

        Return data

    Catch ex As Exception
        Throw ex

    End Try

End Function

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

    Try

        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:

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

    Dim saveFileDLG As New SaveFileDialog()

    Try

        Cursor.Current = Cursors.WaitCursor()

        With saveFileDLG

            Try
                .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
            .ShowDialog()

        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

            fs.Close()

        End If

    Catch eX As Exception
        MessageBox.Show(eX.Message)

    Finally
        Cursor.Current = Cursors.Default()

    End Try

End Sub

Properties

  • 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.

License

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


Written By
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.

web: http://www.clinicmaster.net/
blog: http://bloggingabout.net/blogs/wilson/
MVP Profile: https://mvp.support.microsoft.com/profile/Wilson.Kutegeka
facebook: http://www.facebook.com/Kutegz
twitter: http://www.twitter.com/Kutegz

Comments and Discussions

 
GeneralAn interesting article Pin
rctaubert10-Aug-09 9:36
rctaubert10-Aug-09 9:36 
GeneralRe: An interesting article Pin
Kutegz10-Aug-09 23:43
Kutegz10-Aug-09 23: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.