1

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?

Cheska Abarro
  • 45
  • 1
  • 8

1 Answers1

2

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

Usama Aziz
  • 169
  • 1
  • 10
  • 1
    You shouldn't dispose the stream in `ConvertBytesToImage` which will corrupt the bitmap. Try: `public Image ConvertBytesToImage(byte[] arr) => new Bitmap(new MemoryStream(arr)));` ..... – dr.null Dec 22 '20 at 19:01
  • 1
    JPEG? I thought this way supposed to be a round trip... – Caius Jard Dec 22 '20 at 19:18