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