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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...