Click here to Skip to main content
Click here to Skip to main content
Go to top

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

Comments and Discussions

 
QuestionProblem In hiding text in to Image PinmemberMember 996824722-May-13 5:44 
Questionimage convert Pinmemberklausnewnew18-Apr-13 17:52 
GeneralMy vote of 3 Pinmemberkamalmca2k823-May-11 2:31 
GeneralMy Vote 5 PinmemberNagaraj Muthuchamy22-Dec-08 17:34 
GeneralMy vote of 1 PinmemberGünther M. FOIDL22-Dec-08 7:58 
GeneralMy vote of 1 PinmemberAlexander D. Alexeev21-Dec-08 2:21 
GeneralMy vote of 1 PinmemberR o n n y20-Dec-08 23:40 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140905.1 | Last Updated 21 Dec 2008
Article Copyright 2008 by Imran A Momin
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid