2016-10-04 49 views
1

我正在运行带有mongo数据库的Web服务器。数据库存储记录,其中包括以base64编码字符串形式存储的图片。尝试将图像添加到.net应用程序中的zip文件时内存不足

我正在写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的RAM。

回答

2

你需要处理你的位图。

更改此:

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 
+0

这个解决了它,这样一个愚蠢的事情可以忽略,非常感谢。 – TehDude

+0

@TehDude你很受欢迎,好先生:) – MickyD

相关问题