循环加载图片的时候报错“内存不足”,解决办法,下面是我的个人实例:
原来的写法(会报“内存不足”):
private void aviSaveAs()
{
try
{
OleDbConnection conn = bc.GetConn();
conn.Open();
OleDbCommand cmd = new OleDbCommand("select strPath from tb_VideoPath where ID=1", conn);
string str = cmd.ExecuteScalar().ToString().Trim();
FileInfo fi = new FileInfo(str);
if (fi.Exists)
{
fi.Delete();
}
conn.Close();
aviWriter = new AVIWriter();
//avi中所有图像皆不能小于width及height
avi_frame = aviWriter.Create(str, 1, SWidth, SHeight);
for (int i = 0; i < al.Count; i++)
{
//获得图像
Bitmap cache = new Bitmap(Image.FromFile(al[i].ToString()));
//由于转化为avi后呈现相反,所以翻转
cache.RotateFlip(RotateFlipType.Rotate180FlipX);
//载入图像
aviWriter.LoadFrame(cache);
aviWriter.AddFrame();
//释放文件流资源
imgstream.Dispose();
cache.Dispose();
}
aviWriter.Close();
avi_frame.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
修改后的写法(改用加载文件流,然后可以用完即使释放资源就不会出现内存不足):
private void aviSaveAs()
{
try
{
OleDbConnection conn = bc.GetConn();
conn.Open();
OleDbCommand cmd = new OleDbCommand("select strPath from tb_VideoPath where ID=1", conn);
string str = cmd.ExecuteScalar().ToString().Trim();
FileInfo fi = new FileInfo(str);
if (fi.Exists)
{
fi.Delete();
}
conn.Close();
aviWriter = new AVIWriter();
//avi中所有图像皆不能小于width及height
avi_frame = aviWriter.Create(str, 1, SWidth, SHeight);
for (int i = 0; i < al.Count; i++)
{
//获得图像
Stream imgstream = System.IO.File.Open(al[i].ToString(), FileMode.Open);
Image img = Image.FromStream(imgstream);
//Bitmap cache = new Bitmap(Image.FromFile(al[i].ToString()));
Bitmap cache = new Bitmap(img);
//由于转化为avi后呈现相反,所以翻转
cache.RotateFlip(RotateFlipType.Rotate180FlipX);
//载入图像
aviWriter.LoadFrame(cache);
aviWriter.AddFrame();
//释放文件流资源
imgstream.Dispose();
cache.Dispose();
}
aviWriter.Close();
avi_frame.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}