Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use large bitmaps in .NET?

I'm trying to write a light-weight image viewing application. However, there are system memory limitations with .NET.

When trying to load large bitmaps (9000 x 9000 px or larger, 24-bit), I get a System.OutOfMemoryException. This is on a Windows 2000 PC with 2GB of RAM (of which 1.3GB is used up). It also takes a lot of time to attempt loading the files.

The following code generates this error:

Image image = new Bitmap(filename);
using (Graphics gfx = this.CreateGraphics())
{
    gfx.DrawImage(image, new Point(0, 0));
}

As does this code:

Stream stream = (Stream)File.OpenRead(filename);
Image image = Image.FromStream(stream, false, false);
using (Graphics gfx = this.CreateGraphics())
{
    gfx.DrawImage(image, new Rectangle(0, 0, 100, 100), 4000, 4000, 100, 100, GraphicsUnit.Pixel);
}

Also, it is enough to do just this:

Bitmap bitmap = new Bitmap(filename);
IntPtr handle = bitmap.GetHbitmap();

The latter code was intended for use with GDI. While researching this, I found out that this is in fact a memory issue where .NET tries to allocate twice as much as is needed in a single contigous block of memory.

http://bytes.com/groups/net-c/279493-drawing-large-bitmaps

I know from other applications (Internet Explorer, MS Paint etc.) that it IS possible to open large images, and rather quickly. My question is, how do I use large bitmaps with .NET?

Is there anyway to stream them, or non-memory load them?

like image 526
Reyhn Avatar asked Feb 20 '09 15:02

Reyhn


People also ask

Are bitmap images large?

BMP files are sometimes known as “true images” because they render each individual pixel within the file. They don't compress automatically. This makes them large — a collection of BMP files will rapidly consume lots of memory and space. PNG files display high-quality images, but unlike BMPs, they use compression.

What is the size of a bitmap image?

A bitmap is rectangular and has a spatial dimension, which is the width and height of the image in pixels. For example, this grid could represent a very small bitmap that is 9 pixels wide and 6 pixels high or, more concisely, 9 by 6: By convention, the shorthand dimension of a bitmap is given with the width first.

What affects the size of a bitmap image?

Two factors that affect the size of the bitmap image is resolution and depth. Resolution is the number of pixels contained in the image. Bitmap file is very dependent on the resolution.


1 Answers

One thing just struck me. Are you drawing the entire image and not only the visible part? You should not draw a bigger portion of the image than you are showing in your application, use the x, y, width and heigth parameters to restrict the drawn area.

like image 64
TheCodeJunkie Avatar answered Sep 23 '22 06:09

TheCodeJunkie