Thursday, 28 November 2013

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:\Users\Administrator\Desktop\imageTest.png");
}

Advertisements
Advertisements

4 comments:

  1. thanks, it's very useful for me

    ReplyDelete
  2. Thank you. It's amazing how much code people write for something so simple.

    ReplyDelete
  3. I'm not a developer, I always use this free online image converter to convert image.

    ReplyDelete