![](/img/trans.png)
[英]Out of Memory Exception When Using HttpWebRequest to Stream Large File
[英]Out of Memory Exception when Processing Large Number of Images
我使用以下代碼根據EXIF數據修復圖像的方向
Image FixImageOrientation(Image srce)
{
const int ExifOrientationId = 0x112;
// Read orientation tag
if (!srce.PropertyIdList.Contains(ExifOrientationId)) return srce;
var prop = srce.GetPropertyItem(ExifOrientationId);
var orient = BitConverter.ToInt16(prop.Value, 0);
// Force value to 1
prop.Value = BitConverter.GetBytes((short)1);
srce.SetPropertyItem(prop);
// MessageBox.Show(orient.ToString());
// Rotate/flip image according to <orient>
switch (orient)
{
case 1:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
return srce;
case 2:
srce.RotateFlip(RotateFlipType.RotateNoneFlipX);
return srce;
case 3:
srce.RotateFlip(RotateFlipType.Rotate180FlipNone);
return srce;
case 4:
srce.RotateFlip(RotateFlipType.Rotate180FlipX);
return srce;
case 5:
srce.RotateFlip(RotateFlipType.Rotate90FlipX);
return srce;
case 6:
srce.RotateFlip(RotateFlipType.Rotate90FlipNone);
return srce;
case 7:
srce.RotateFlip(RotateFlipType.Rotate270FlipX);
return srce;
case 8:
srce.RotateFlip(RotateFlipType.Rotate270FlipNone);
return srce;
default:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
return srce;
}
}
我像這樣處理大量圖像
for (x= 0; x<list.Count; x++)
{
filepath= list.ElementAt(x);
Bitmap image = new Bitmap(FixImageOrientation(Bitmap.FromFile(filepath)));
//Do long processing and at the end i do image.dispose();
image.dispose();
}
但是當處理大量圖像時,我在
Bitmap image = new Bitmap(FixImageOrientation(Bitmap.FromFile(filepath)));
我為什么得到這個..我把這個圖像放在循環的末尾。
在您的代碼中,您創建了兩個位圖,但只放置了一個。 更改您的代碼:
using(var source = Bitmap.FromFile(filepath)) {
using(var image = new Bitmap(FixImageOrientation(source))) {
// ... do long processing
}
}
這應該可以解決您的問題。
正如您在此答案中可以找到的https://stackoverflow.com/a/7520919/6439999調用處置不一定釋放內存。 這是垃圾收集器的任務。 我假設您正在將圖像快速加載到內存中。 問題是,垃圾收集不時進行。 如果通過創建新對象使用大量內存,則垃圾回收可能會減慢再次釋放內存的速度。
您可以嘗試使用GC.Collect()從循環內部直接調用它。 如果這還不夠,您還可以嘗試使用阻塞參數,該參數將暫停線程,直到GC運行完成。
作為另一種方法,您可以將項目設置為x64編譯,這將使程序可以訪問超過1GB的內存。 但是,使用此解決方案,您只會將問題進一步推向前進。
湯瑪士
超出存儲記錄范圍 ,可能的解決方案是:
在程序中使用using語句限制數據庫對象的范圍
使用后將空值分配給列表
放置連接對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.