Yeah, you can do it that way or you can save it as a byte array depending on what will better fit your needs. When you use serialization things tend to bloat a little, so it will definitely work, but it will take up less space if you use a byte array instead of a serialized image. You can still expose the property as an Image so that you are always dealing with it in that manner, but within the property you can save it as a byte array if you wanted to:
Public Property MyImageField() As Image
Get
'-- Establish Locals
Dim r As Bitmap
Dim stream As System.IO.MemoryStream
'-- See if there is anything to return
If CurrentRow.Item("MyImageField") IsNot DbNull.Value AndAlso _
CType(CurrentRow.Item("MyImageField"), Byte()).Length > 0 Then
stream = New System.IO.MemoryStream(CTYpe(CurrentRow.Item("MyImageField"), Byte()))
r = Bitmap.FromStream(stream)
stream.Close()
Else
'-- You can create a blank image if you would like so a valid image is always returned. Or possibly
' a default image.
r = New Bitmap(16,16)
End If
Return CType(r. Image)
End Get
Set(ByVal value As Image)
'-- Establish Locals
Dim stream As New System.IO.MemoryStream()
'-- Save the image to a stream
r.Save(stream,System.Drawing.Imaging.ImageFormat.Jpeg)
'-- Now save the stream as a byte array
Me.CurrentRow.Item("MyImageField") = StreamToByteArray(stream)
'-- Clean Up
stream.Close()
End Set
End Property
''' <summary>
''' Converts a stream into a byte array
''' </summary>
''' <param name="MediaStream"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function StreamToByteArray(ByVal MediaStream As System.IO.Stream) As Byte()
'-- Establish Locals
Dim loReturn(CType(MediaStream.Length, Integer)) As Byte
Dim laBuffer(30000) As Byte
Dim lnBytesRead As Integer
Dim lnCurrent As Integer = 0
'-- Move to the beginning of the stream
MediaStream.Seek(0, IO.SeekOrigin.Begin)
'-- Read the first chunk
lnBytesRead = MediaStream.Read(laBuffer, 0, laBuffer.Length)
While lnBytesRead <> 0
'-- Write to the return buffer
Array.Copy(laBuffer, 0, loReturn, lnCurrent, lnBytesRead)
'-- Update the current index
lnCurrent += lnBytesRead
'-- Read the next chunk
lnBytesRead = MediaStream.Read(laBuffer, 0, laBuffer.Length)
End While
'-- Return the array
Return loReturn
End Function