Visual Basic: Convert an image stored in a SQL Server varbinary(max) data type back to an image that can be shown in a PictureBox or DataGridView

Platform:Visual Basic
Task:Convert an image stored in a SQL Server varbinary(max) data type back to an image that can be shown in a PictureBox or DataGridView
Discussion:
You're storing images in SQL Server and need to build a VB .Net application that shows the picture. Here is a link that looks helpful: http://www.dotnetspider.com/projects/512-Store-Retrieve-pdf-txt-doc-Images-Sql-server-database.aspx
Example:
    ''' <summary>
    ''' Converts a Binary Large Object to an Image.  To be used to convert images stored in SQL Server varbinary(max) data type back into an image that can be shown
    ''' in a DataGridView or PictureBox. 
    ''' </summary>
    ''' <param name="BLOBObject">The BLOB object to be converted to an image.</param>
    ''' <returns>Image</returns>
    ''' <remarks>
    ''' Example showing how to convert a record from a DataTable's BindingSource into an Image:  
    ''' Dim CurrentRow As DataRowView = Me.BLOBTestBindingSource.Current
    ''' PictureBox1.Image = ConvertBLOBToImage(CurrentRow.Item("BLOBData"))
    ''' </remarks>
    Private Function ConvertBLOBToImage(ByVal BLOBObject As Object) As Image
        Try
            If Not BLOBObject Is Nothing Then
                Dim MyMemoryStream As System.IO.MemoryStream = Nothing 'create a memory stream
                Dim MyImage As Image = Nothing 'create an image to hold the converted byte data
                Dim MyImageBytes As Byte() = Nothing 'create a byte array to hold the blob
                MyImageBytes = CType(BLOBObject, Byte()) 'convert the blob object to bytes

                'Read the byte array into a MemoryStream
                MyMemoryStream = New System.IO.MemoryStream(MyImageBytes, 0, MyImageBytes.Length)

                'Create the new Image from the stream
                MyImage = Image.FromStream(MyMemoryStream)
                Return MyImage
            Else
                Return Nothing
            End If
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
Back to Index