DAL Should like following when inserting a image. I used the Enterprise Library to data access. Data type of EmployerImage is image @ SQL Server table.
Public Sub Insert()
Try
Dim DB As Database = DatabaseFactory.CreateDatabase(CWB_DBCONNECTION_STRING)
Dim DBC As DbCommand = DB.GetStoredProcCommand(EMPLOYERS_INSERT)
DB.AddInParameter(DBC, "@EmployerID", DbType.Int64, EmployerID)
If EmployerImage Is Nothing Then
DB.AddInParameter(DBC, "@EmployerImage", DbType.Binary, Nothing)
Else
DB.AddInParameter(DBC, "@EmployerImage", DbType.Binary, GetByteArrayFromImage(EmployerImage))
End If
DB.ExecuteNonQuery(DBC)
Catch ex As Exception
Throw
End Try
End Sub
Getting byte array from the image you need to create a function like following.
Public Function GetByteArrayFromImage(ByVal img As Bitmap) As Byte()
Try
Dim ms As New System.IO.MemoryStream
img.Save(ms, Imaging.ImageFormat.Bmp)
Dim outBytes(CInt(ms.Length - 1)) As Byte
ms.Seek(0, System.IO.SeekOrigin.Begin)
ms.Read(outBytes, 0, CInt(ms.Length))
Return outBytes
Catch ex As Exception
Return Nothing
Throw
End Try
End Function
Calling the image from the SQL Server
Public Sub SelectRow()
Dim DB As Database = DatabaseFactory.CreateDatabase(CWB_DBCONNECTION_STRING)
Dim DBC As DbCommand = DB.GetStoredProcCommand(EMPLOYERS_GETBYID)
Try
DB.AddInParameter(DBC, "@EmployerID", DbType.Int64, Me.EmployerID)
Using DR As IDataReader = DB.ExecuteReader(DBC)
With DR
Do While .Read
If Not IsDBNull(.Item("EmployerImage")) Then
EmployerImage = GetImageFromByteArray(.Item("EmployerImage"))
Else
EmployerImage = Nothing
End If
Loop
End With
If (Not DR Is Nothing) Then
DR.Close()
End If
End Using
Catch ex As Exception
Throw
Finally
DBC.Dispose()
End Try
End Sub
Getting saved image from SQL Server table
Public Function GetImageFromByteArray(ByVal bytes As Byte()) As Bitmap
Try
Return CType(Bitmap.FromStream(New IO.MemoryStream(bytes)), Bitmap)
Catch ex As Exception
Return Nothing
Throw
End Try
End Function