简体   繁体   中英

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?

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 convert byte[] to a string or vice-versa, you can refer to this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM