Cheska Abarro
Cheska Abarro

Reputation: 65

Convert Image to Byte array and vice versa

This may be an existing question but the answers I got is not exactly what I'm looking for.

In C# Winforms, I want to convert the image (not the path) from the picturebox and convert it into Byte array and display that Byte array in label.

Currently, this is what I have.

Byte[] result = (Byte[]) new ImageConverter().ConvertTo(pbOrigImage.Image, typeof(Byte[]));

Then, after displaying the Byte array in label, I want to convert it from Byte array to image. I currently don't have codes when it comes to image to Byte array conversion. But is this possible?

Upvotes: 1

Views: 3354

Answers (1)

Usama Aziz
Usama Aziz

Reputation: 279

You can use the following methods for conversion from byte[] to Image,

public byte[] ConvertImageToBytes(Image img)
    {
        byte[] arr;
        using (MemoryStream ms = new MemoryStream())
        {
            Bitmap bmp = new Bitmap(img);
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            arr = ms.ToArray();
        }
        return arr;
    }

    public Image ConvertBytesToImage(byte[] arr)
    {
        using (MemoryStream ms = new MemoryStream(arr))
        {
            return Bitmap.FromStream(ms);
        }
    }

To convertbyte[] to a string or vice-versa, you can refer to this

Upvotes: 2

Related Questions