Convert Image to Byte Array and Byte Array to Image in c#

Description

In this article, I am going to give C# code examples to Convert Image to Byte Array and Byte Array to Image using ImageConverter and MemoryStream.

Summary

Convert Image File into Byte Array in C#

public static byte[] ImageToByteArrayFromFilePath(string imagefilePath)
    {
        byte[] imageArray = File.ReadAllBytes(imagefilePath);
        return imageArray;
    }

Convert Image to Byte Array in C# using ImageConverter

Note: To use the classes ImageConverter and Image, you need to add the reference System.Drawing

public static byte[] ImageToByteArray(string imagefilePath)
{
    System.Drawing.Image image = System.Drawing.Image.FromFile(imagefilePath);
    byte[] imageByte = ImageToByteArraybyImageConverter(image);
    return imageByte;
}

private static byte[] ImageToByteArraybyImageConverter(System.Drawing.Image image)
{
    ImageConverter imageConverter = new ImageConverter();
    byte[] imageByte = (byte[])imageConverter.ConvertTo(image, typeof(byte[]));
    return imageByte;
}

Convert Image to Byte Array in C# using MemoryStream

Note: To use the classes ImageConverter and Image, you need to add the reference System.Drawing;

public static byte[] ImageToByteArray(string imagefilePath)
{
    System.Drawing.Image image = System.Drawing.Image.FromFile(imagefilePath);
    byte[] imageByte = ImageToByteArraybyMemoryStream(image);
    return imageByte;
}

private static byte[] ImageToByteArraybyMemoryStream(Image image)
{
    MemoryStream ms = new MemoryStream();
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    return ms.ToArray();
}

Convert Byte Array to Image in C# using MemoryStream

public static Image ByteArrayToImagebyMemoryStream(byte[] imageByte)
{
    MemoryStream ms = new MemoryStream(imageByte);
    Image image = Image.FromStream(ms);
    return image;
}

Convert Byte Array to Image File in C# using MemoryStream

public static void ByteArrayToImageFilebyMemoryStream(byte[] imageByte)
{
    MemoryStream ms = new MemoryStream(imageByte);
    Image image = Image.FromStream(ms);
    image.Save(@"C:\UsersAdministratorDesktopimageTest.png");
}

Advertisement

4 thoughts on “Convert Image to Byte Array and Byte Array to Image in c#”

Leave a Comment