[英]Out of Memory Exception in C#
我是C#的新手。 因此,我不太確定我的程序存在什么問題。 該程序適用於小圖像,但當它處理大約A4大小的大圖像時,它顯示“內存不足”。 但是,如果程序無法處理大圖像,那么該程序將毫無用處。 我該如何解決這個問題? 謝謝。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
//Bitmap objects
//input image
Bitmap bmOrg = (Bitmap)Bitmap.FromFile(@"C:\B.png");
Bitmap bmTransparentLayover = new Bitmap(bmOrg.Width, bmOrg.Height);
//Create Graphic Objects.
Graphics gOriginal = Graphics.FromImage(bmOrg);
Graphics gTransparentLayover = Graphics.FromImage(bmTransparentLayover);
//Set Transparent Graphics back ground to an "odd" color
// that hopefully won't be used to
//Be changed to transparent later.
gTransparentLayover.FillRectangle
( Brushes.Pink,
new Rectangle
(0,
0,
bmTransparentLayover.Width,
bmTransparentLayover.Height
)
);
//Draw "transparent" graphics that will look through
// the overlay onto the original.
//Using LimeGreen in hopes that it's not used.
Point[] points = new Point[5];
points[0] = new Point(130, 140);
points[1] = new Point(130, 370);
points[2] = new Point(420, 370);
points[3] = new Point(420, 140);
points[4] = new Point(130, 140);
System.Drawing.Drawing2D.GraphicsPath gp = new
System.Drawing.Drawing2D.GraphicsPath();
gp.AddPolygon(points);
gTransparentLayover.FillPath(Brushes.LimeGreen, gp);
//Now make the LimeGreen Transparent to see through overlay.
bmTransparentLayover.MakeTransparent(Color.LimeGreen);
//draw the overlay on top of the original.
gOriginal.DrawImage(bmTransparentLayover,
new Rectangle(0, 0, bmTransparentLayover.Width, bmTransparentLayover.Height));
//Create new image to make the overlays background tranparent
Bitmap bm3 = new Bitmap(bmOrg);
bm3.MakeTransparent(Color.Pink);
//Save file.
//to save the output image
bm3.Save(@"save.png",System.Drawing.Imaging.ImageFormat.Png);
Image img = new Bitmap(480, 480);
//the background image
img = Image.FromFile(@"a.png");
Graphics g = Graphics.FromImage(img);
//to save the combined image
g.DrawImage(Image.FromFile(@"save.png"), new Point(-50, -70));
img.Save(@"final.png", ImageFormat.Png);
}
}
}
這是一張9992x8750的圖片
是的,您處於32位進程的危險區域。 該映像需要大量連續的地址空間,334 MB。 在程序啟動后立即加載圖像時,您可以輕松獲得該圖像。 你可以獲得大約650兆字節,給予或接受。
但是當你的程序分配和釋放內存並加載一些程序集時,那就會從那里下山。 地址空間變得碎片化,分配之間的漏洞越來越小。 只需加載具有笨拙基址的DLL,就可以突然將最大的漏洞削減兩倍以上。 問題不在於可用的虛擬內存總量,它可以是千兆字節或更多,它是最大可用塊的大小。 過了一會兒,90兆字節的分配失敗並不完全是不尋常的。 只要一個分配失敗,你仍然可以分配一堆,比方說,50兆字節的塊。
地址空間碎片無法解決問題,您無法修復Bitmap類存儲像素數據的方式。 但是,請指定64位版本的Windows作為程序的要求。 它提供了大量的虛擬內存,碎片是一個非問題。 如果您想追逐它,那么您可以使用SysInternals的VMMap實用程序深入了解VM布局。 請注意您可能遇到的信息過載。
我懷疑你的主要問題是你同時使用了許多位圖和圖形實例。
可能值得嘗試重新組織您的代碼,以便盡可能少地出現這些代碼,使用.Dispose()刪除您已完成的項目。
嘗試使用Windows 64位,這是大多數內存問題的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.