0

I have tried to convert binary data to Image. here is my code:

 Byte[] bytes = (byte[])(reader["Avatar"]);
 fs1.Write(bytes, 0, bytes.Length);
 pictureBox1.Image = Image.FromFile("image.jpg");
 pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
 pictureBox1.Refresh();

but the wrong is out of bound memory exception in line : "pictureBox1.Image = Image.FromFile("image.jpg");" I do not know why this happen, please help me

Musa
  • 96,336
  • 17
  • 118
  • 137
famfamfam
  • 396
  • 3
  • 8
  • 31
  • 1
    How are the first two lines related to the rest? If `fs1` is some form of open stream against `image.jpg` it may need to be closed before you can call `FromFile`, but you've not shown enough code for me to know if that's so. – Damien_The_Unbeliever Jul 12 '12 at 07:36
  • possible duplicate of [Why does my form throw an OutOfMemory exception while trying to load image?](http://stackoverflow.com/questions/10769397/why-does-my-form-throw-an-outofmemory-exception-while-trying-to-load-image) – Hans Passant Jul 12 '12 at 07:44

3 Answers3

2

If fs1 is a stream you probably should close it before you access that file in the next line. Note that you can also create the image in memory and avoid the file system completely.

Sebastian
  • 7,729
  • 2
  • 37
  • 69
2

Try with this method:

    public Image ImageFromBytes(byte[] bytes)
    {
        using(var ms = new MemoryStream(bytes))
        {
          return Image.FromStream(ms);
        }
    }
laszlokiss88
  • 4,001
  • 3
  • 20
  • 26
0

You mast Close and Dispose your stream:

fs1.Write(bytes, 0, bytes.Length);
//Make sure you closed your stream
fs1.Close();
// You should call Dispose too.
fs1.Dispose();
pictureBox1.Image = Image.FromFile("image.jpg");

or enclose your writing file procces in using block:

using (Stream fs1 ...)
{
    ...
    fs1.Write(bytes, 0, bytes.Length);
}  
Ria
  • 10,237
  • 3
  • 33
  • 60