Click here to Skip to main content
15,922,015 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Can you help me?
I write a code that read a png image from file and show with control.
I want read image to stream and set
C#
panel1.BackgroundImage = Image.FromStream(memStream);
but
when use
C#
control.BackgroundImage = Image.FromStream()
, occur "out of memory" exception.
when use
C#
control.Image = Image.FromStream
or
C#
control.BackgroundImage = Image.FromFile
, that is work.

image file size is 5KB.

my code is :
C#
try
{
if (System.IO.File.Exists(imgSource))
{
using (FileStream localFileStream = new FileStream(imgSource, FileMode.Open))
{
using (MemoryStream memStream = new MemoryStream())
{
   int bytesRead;
   byte[] buffer = new byte[1024];

   while ((bytesRead = localFileStream.Read(buffer, 0, buffer.Length)) > 0)
   {
      memStream.Write(buffer, 0, bytesRead);
   }
   retIMG = Image.FromStream(memStream);

   pictureBox1.Image = retIMG;		// is work
   label1.Image = retIMG;		// is work
   button1.Image = retIMG;		// is work
   button1.BackgroundImage = retIMG;	// don't work
   groupBox1.BackgroundImage = retIMG;	// don't work
   panel1.BackgroundImage = retIMG;	// don't work
}
}
}
}
catch
{
MessageBox.Show("Exception");
}
Posted
Comments
BillWoodruff 14-Oct-11 21:32pm    
What's the reason you are using a stream here, rather than using Image.FromFile(filePath) ? I don't know if this is relevant, but the MSDN docs on Image.FromStream comment: "You must keep the stream open for the lifetime of the Image. The stream is reset to zero if this method is called successively with the same stream."

http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900