Click here to Skip to main content
13,044,539 members (60,875 online)
Click here to Skip to main content
Add your own
alternative version

Stats

101.3K views
24 bookmarked
Posted 20 Dec 2008

Convert Image File to Bytes and Back

, 20 Dec 2008
Rate this:
Please Sign up or sign in to vote.
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()

''' <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

''' <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

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

Share

About the Author

Imran A Momin
Software Developer (Junior)
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionProblem In hiding text in to Image Pin
Member 996824722-May-13 5:44
memberMember 996824722-May-13 5:44 
Questionimage convert Pin
klausnewnew18-Apr-13 17:52
memberklausnewnew18-Apr-13 17:52 
GeneralMy vote of 3 Pin
kamalmca2k823-May-11 2:31
memberkamalmca2k823-May-11 2:31 
GeneralMy Vote 5 Pin
Nagaraj Muthuchamy22-Dec-08 17:34
memberNagaraj Muthuchamy22-Dec-08 17:34 
GeneralMy vote of 1 Pin
Günther M. FOIDL22-Dec-08 7:58
memberGünther M. FOIDL22-Dec-08 7:58 
GeneralMy vote of 1 Pin
Alexander D. Alexeev21-Dec-08 2:21
memberAlexander D. Alexeev21-Dec-08 2:21 
GeneralMy vote of 1 Pin
R o n n y20-Dec-08 23:40
memberR 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 21 Dec 2008
Article Copyright 2008 by Imran A Momin
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid