Introduction
I wrote down this code when on of my project needed to store the image files into database in the form of array of bytes. This bytes were saved in image type of column of database.
Using the Code
Here is the function that convert the image file to bytes()
Public Function ConvertImageFiletoBytes(ByVal ImageFilePath As String) As Byte()
Dim _tempByte() As Byte = Nothing
If String.IsNullOrEmpty(ImageFilePath) = True Then
Throw New ArgumentNullException("Image File Name Cannot be Null or Empty", "ImageFilePath")
Return Nothing
End If
Try
Dim _fileInfo As New IO.FileInfo(ImageFilePath)
Dim _NumBytes As Long = _fileInfo.Length
Dim _FStream As New IO.FileStream(ImageFilePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim _BinaryReader As New IO.BinaryReader(_FStream)
_tempByte = _BinaryReader.ReadBytes(Convert.ToInt32(_NumBytes))
_fileInfo = Nothing
_NumBytes = 0
_FStream.Close()
_FStream.Dispose()
_BinaryReader.Close()
Return _tempByte
Catch ex As Exception
Return Nothing
End Try
End Function
Here is the function that convert Array of Bytes to Image File
Public Function ConvertBytesToImageFile(ByVal ImageData As Byte(), ByVal FilePath As String) As Result
If IsNothing(ImageData) = True Then
Return Result.Failure
End If
Try
Dim fs As IO.FileStream = New IO.FileStream(FilePath, IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
Dim bw As IO.BinaryWriter = New IO.BinaryWriter(fs)
bw.Write(ImageData)
bw.Flush()
bw.Close()
fs.Close()
bw = Nothing
fs.Dispose()
Return Result.Success
Catch ex As Exception
Return Result.Failure
End Try
End Function
While writting down this code i came across one function which proved to be handy. I am also posting this code down. This code is to convert the bytes and image file which evet to Memory Stream Object
Public Function ConvertBytesToMemoryStream(ByVal ImageData As Byte()) As IO.MemoryStream
Try
If IsNothing(ImageData) = True Then
Return Nothing
End If
Return New System.IO.MemoryStream(ImageData)
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function ConvertImageFiletoMemoryStream(ByVal ImageFilePath As String) As IO.MemoryStream
If String.IsNullOrEmpty(ImageFilePath) = True Then
Return Nothing
End If
Return ConvertBytesToMemoryStream(ConvertImageFiletoBytes(ImageFilePath))
End Function
Points of Interest
Its a good way around to save and edit the image direct from the database. The main disadvantage is that it can take a lot of memory space in the database making the database a very bulky.
Bibliography
I have gone through some examples over the net and MSDN
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.