Smart PictureBox Control
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.
<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()
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.
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:
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 toTrue
, 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.