Click here to Skip to main content
16,021,449 members
Articles / Programming Languages / Visual Basic
Article

Convert Image File to Bytes and Back

Rate me:
Please Sign up or sign in to vote.
2.86/5 (11 votes)
20 Dec 2008CPOL 133.1K   25   7
Its a small piece of code, that converts the image file into array of byte which can be stored into database at type image

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()

VB.NET
''' <summary>
''' Converts the Image File to array of Bytes
''' </summary>
''' <param name="ImageFilePath">The path of the image file</param>
''' <returns></returns>
''' <remarks></remarks>
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

VB.NET
''' <summary>
''' Converts array of Bytes to Image File
''' </summary>
''' <param name="ImageData">The array of bytes which contains image binary data</param>
''' <param name="FilePath">The destination file path.</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function ConvertBytesToImageFile(ByVal ImageData As Byte(), ByVal FilePath As String) As Result
    If IsNothing(ImageData) = True Then
        Return Result.Failure
        'Throw New ArgumentNullException("Image Binary Data Cannot be Null or Empty", "ImageData")
    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

VB.NET
''' <summary>
    ''' Converts array of bytes to Memoey Stream
    ''' </summary>
    ''' <param name="ImageData">The array of bytes which contains image binary data</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ConvertBytesToMemoryStream(ByVal ImageData As Byte()) As IO.MemoryStream
        Try
            If IsNothing(ImageData) = True Then
                Return Nothing
                'Throw New ArgumentNullException("Image Binary Data Cannot be Null or Empty", "ImageData")
            End If
            Return New System.IO.MemoryStream(ImageData)
        Catch ex As Exception
            Return Nothing
        End Try
        End Function



''' <summary>
    ''' Converts the Image File to Memory Stream
    ''' </summary>
    ''' <param name="ImageFilePath"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ConvertImageFiletoMemoryStream(ByVal ImageFilePath As String) As IO.MemoryStream
        If String.IsNullOrEmpty(ImageFilePath) = True Then
            Return Nothing
            ' Throw New ArgumentNullException("Image File Name Cannot be Null or Empty", "ImageFilePath")
        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 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionProblem In hiding text in to Image Pin
Member 996824722-May-13 5:44
Member 996824722-May-13 5:44 
Questionimage convert Pin
klausnewnew18-Apr-13 17:52
klausnewnew18-Apr-13 17:52 
GeneralMy vote of 3 Pin
kamalmca2k823-May-11 2:31
kamalmca2k823-May-11 2:31 
GeneralMy Vote 5 Pin
Nagaraj Muthuchamy22-Dec-08 17:34
professionalNagaraj Muthuchamy22-Dec-08 17:34 
GeneralMy vote of 1 Pin
Günther M. FOIDL22-Dec-08 7:58
Günther M. FOIDL22-Dec-08 7:58 
GeneralMy vote of 1 Pin
Alexander D. Alexeev21-Dec-08 2:21
Alexander D. Alexeev21-Dec-08 2:21 
GeneralMy vote of 1 Pin
R o n n y20-Dec-08 23:40
R o n n y20-Dec-08 23:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.