Convert Image to Byte Array and Byte Array to Image

In many situations you may forced to convert image to byte array. It is useful in many scenarios because byte arrays can be easily compared, compressed, stored, or converted to other data types. You can make this conversion in many ways, but here you can see the fastest and memory efficient conversion in two ways.

Using MemoryStream

The Image object has a save function which allows developers to save an image to a file in any image format supported by the .NET Framework. Here this save function applied on the MemoryStream object, while specifying an image format. Since the object is in memory, it can easily be converted into a byte array with the ToArray function from the MemoryStream object.



C# Convert Image to Byte Array

Both MemoryStream and Image have a dispose method, make sure you are Disposing of them as this can cause MemoryLeaks. Here we use the using blocks which ensures that it calls Dispose() method after the using-block is over, even if the code throws an exception. Also here use a RawFormat property of Image parameter which returns the file format of the image.

Using ImageConverter

ImageConverter class can be used to convert Image objects from one data type to another.



Convert ByteArray to Image



VB.Net Convert Image to Byte Array

The following program first convert an Image to ByteArray and then convert that byteArray to Image and loads in a picture box.

Source Code | C#

Source Code | Vb.Net

NEXT.....Numeric Only TextBox Control