试图在.net应用程序中将图像添加到zip文件时内存不足
本文关键字:添加 zip 文件 内存不足 图像 net 应用程序 | 更新日期: 2023-09-27 18:11:31
我正在运行一个web服务器与mongo数据库。数据库存储记录,其中包括以base64编码字符串存储的图片。
我正在编写一个api调用,从记录中获取这些图像中的几个,将它们构建为.jpg图像,并将它们添加到存储在服务器上的zip文件中。
我遇到的问题是,即使图像的总大小小于10mb,每个图像大约为500kb,在只有几个记录之后,调用也会返回一个OutOfMemory异常。下面是我使用的代码:
using (ZipFile zipFile = new ZipFile())
{
var i = 0;
foreach (ResidentialData resident in foundResidents)
{
MemoryStream tempstream = new MemoryStream();
Image userImage1 = LoadImage(resident.AccountImage);
Bitmap tmp = new Bitmap(userImage1);
tmp.Save(tempstream, ImageFormat.Jpeg);
tempstream.Seek(0, SeekOrigin.Begin);
byte[] imageData = new byte[tempstream.Length];
tempstream.Read(imageData, 0, imageData.Length);
zipFile.AddEntry(i + " | " + resident.Initials + " " + resident.Surname + ".jpg", imageData);
i++;
tempstream.Dispose();
}
zipFile.Save(@"C:'temp'test.zip");
}
你知道是什么在吞噬所有的内存吗?我不明白这是怎么可能的,因为它运行的机器有32gb的内存。
你需要处理你的位图。
改变:
tempstream.Dispose();
…:
tempstream.Dispose();
tmp.Dispose();
你可能想看看使用using()
块,因为它们允许你定义;分配并自动释放资源。
。
using (var x = new SomethingThatNeedsDisposing())
{
// do something with x
} // <----- at this point .NET will call x.Dispose() for you