How to Convert Image to Byte Array in C# ?

Are you looking at a way to convert image to byte array in C#?. You can convert an Bitmap image to byte array in C# using the  BinaryReader’s ReadByte method. Here are the steps that you need to follow for the conversion.

  • Create an instance of the FileStream and specify the file path along with the File Mode and the File Access.
  • Create an instance of the BinaryReader and specify the fileStream instance as parameter for the constructor.
  • Read the Byte one by one from the Binary reader and assign it to the Byte Array that you want to return.

How to Convert an Image to Byte Array in C# ?

Here’s a code snippet demonstrating how you can do it.

using System;
using System.IO;
namespace DeveloperPublishConsoleApp
{
    class Program
    {
        //Step to convert the image to the Byte Array
        public static byte[] ConvertImageToByteArray(string imagePath)
        {
            byte[] imageByteArray = null;
            FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
            using (BinaryReader reader = new BinaryReader(fileStream))
            {
                imageByteArray = new byte[reader.BaseStream.Length];
                for (int i = 0; i < reader.BaseStream.Length; i++)
                    imageByteArray[i] = reader.ReadByte();
            }
            return imageByteArray;
        }

        static void Main(string[] args)
        {
            // 1. Step to convert the image to the Byte Array
            string imagePath = @"D:\1.bmp";
            byte[] result = ConvertImageToByteArray(imagePath);
           
        }       
    }
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...