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.