1

I have a problem when I try to convert stream to image. It shows me an error in: Image returnImage = Image.FromStream(ms);

if (reader[12] != System.DBNull.Value)
{
    Byte[] image = (Byte[])reader[12];
    c.image = byteArrayToImage(image);
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream();
    ms.Write(byteArrayIn, 0, byteArrayIn.Length);
    ms.Seek(0, SeekOrigin.Begin);
    ms.Close();
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}
5
  • what kind of error did you get ? Commented Jun 5, 2014 at 8:49
  • As an aside, you can do new MemoryStream(byteArrayIn) and save yuorself the Write and Seek calls. Commented Jun 5, 2014 at 8:51
  • 2
    Yeah. It shows you an error. Are we supposed to guess or put work in, or can you - ah - be smart enough to actually tell us the error, too? Hint: One look at the code, the error and you may realize READING the error sort of makes sense. Commented Jun 5, 2014 at 8:52
  • a first it showed me that it can't read a closed stream, i delete ms.close() now it shows me Le paramètre n'est pas valide. (invalid parameter) Commented Jun 5, 2014 at 8:54
  • @user3710293 See the answers Dmitry and I gave and pick the one you like better. The "Invalid Pararmeter" error is thrown because you pass a closed stream to the FromStream method. Commented Jun 5, 2014 at 8:55

2 Answers 2

4

You should not close the stream so soon:

   ms.Close();  // <- That's wrong:
   // You can't create an image from a disposed stream
   Image returnImage = Image.FromStream(ms); 

Do it like that:

  ...
  using (MemoryStream ms = new MemoryStream()) {
    ms.Write(byteArrayIn, 0, byteArrayIn.Length);
    ms.Seek(0, SeekOrigin.Begin);

    return Image.FromStream(ms);
  }
Sign up to request clarification or add additional context in comments.

Comments

3
MemoryStream ms = new MemoryStream();
ms.Write(byteArrayIn, 0, byteArrayIn.Length);
ms.Seek(0, SeekOrigin.Begin);
ms.Close();  // <-- Remove this line

Image returnImage = Image.FromStream(ms);
return returnImage;

In this code you close the stream before creating the image. You can not read from a closed stream. Change your code to this:

using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

That code may generate GDI+ errors. So you don't have to be afraid of not disposing of the stream at all. The garbage collector will do this anyway, so if you get errors in GDI+, use this:

MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.