简体   繁体   中英

Convert Byte to Image jpg

i have a problem with convert byte[] to .jpg file. When I try to convert byte, I got a exception in this method:

using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
{
   ms.Write(bytes, 0, bytes.Length);
   Image image = Image.FromStream(ms, true, false);
}

Exception:

The parameter is invalid in System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)

Any suggestion?

Solution * : Remove the line: ms.Write(bytes, 0, bytes.Length);

* If this doesn't work, the bytes array doesn't contain valid image data.


Reason:

This line initializes a MemoryStream with the bytes in a byte array. It will start the stream at position 0 (the beginning):

using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))

and in your case it can be simplified to:

using (MemoryStream ms = new MemoryStream(bytes))

This line then writes the same bytes into the stream. It will leave your stream at position bytes.Length (the end):

ms.Write(bytes, 0, bytes.Length);

This line will try to read an image from the stream starting at the current position (the end). Since 0 bytes don't make an image, it fails giving you the exception:

Image image = Image.FromStream(ms, true, false);

As noted by Jimi, it might be better wrapping this up into a method:

public static Image ImageFromByteArray(byte[] bytes)
{
    using (MemoryStream ms = new MemoryStream(bytes))
    using (Image image = Image.FromStream(ms, true, true))
    {
        return (Image)image.Clone();
    }
}

The reason for using Clone() is that it can cause trouble saving the image if the original stream has been disposed of.

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