C#线程中Image.FromFile()处提示内存不足
遥新 2014-05-22 03:00:40 我在一个窗体的Load事件中创建了一个线程,在线程中用while循环判断一个文件夹下是否存在特定名称的三张jpg图片,当这三张图片出现时将它们显示在窗体的三个pictureBox中。线程如下:
private void thread_refresh()
{
string pic_name1 = "C:\\WasteManage\\DigRec\\image\\pic-cam1.jpg";
string pic_name2 = "C:\\WasteManage\\DigRec\\image\\pic-cam2.jpg";
string pic_name3 = "C:\\WasteManage\\DigRec\\image\\pic-cam3.jpg";
bool pic_exist1 = File.Exists(pic_name1);
bool pic_exist2 = File.Exists(pic_name2);
bool pic_exist3 = File.Exists(pic_name3);
while (!pic_exist1 || !pic_exist2 || !pic_exist3)
{
pic_exist1 = File.Exists(pic_name1);
pic_exist2 = File.Exists(pic_name2);
pic_exist3 = File.Exists(pic_name3);
}
Image pic1 = Image.FromFile("C:\\WasteManage\\DigRec\\image\\pic-cam1.jpg");
Image bmp1 = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics g1 = Graphics.FromImage(bmp1);
g1.DrawImage(pic1, new Rectangle(0, 0, bmp1.Width, bmp1.Height), new Rectangle(0, 0, pic1.Width, pic1.Height), GraphicsUnit.Pixel);
g1.Flush();
g1.Dispose();
pic1.Dispose();
pictureBox1.Image = bmp1;
Image pic2 = Image.FromFile("C:\\WasteManage\\DigRec\\image\\pic-cam2.jpg");
Image bmp2 = new Bitmap(pictureBox2.Width, pictureBox2.Height);
Graphics g2 = Graphics.FromImage(bmp2);
g2.DrawImage(pic2, new Rectangle(0, 0, bmp2.Width, bmp2.Height), new Rectangle(0, 0, pic2.Width, pic2.Height), GraphicsUnit.Pixel);
g2.Flush();
g2.Dispose();
pic2.Dispose();
pictureBox2.Image = bmp2;
Image pic3 = Image.FromFile("C:\\WasteManage\\DigRec\\image\\pic-cam3.jpg");
Image bmp3 = new Bitmap(pictureBox3.Width, pictureBox3.Height);
Graphics g3 = Graphics.FromImage(bmp3);
g3.DrawImage(pic3, new Rectangle(0, 0, bmp3.Width, bmp3.Height), new Rectangle(0, 0, pic3.Width, pic3.Height), GraphicsUnit.Pixel);
g3.Flush();
g3.Dispose();
pic3.Dispose();
pictureBox3.Image = bmp3;
}
现在遇到问题就是运行时经常会出错,在红色代码处提示内存不足,但不是每次都出错,网上查了一下有人说可能是没有连续的内存空间存放图片,我的图片每张是5MB多,是这个原因吗?该如何解决?