Error in memory while loading Bitmap

I work with large images (e.g. 16000x9440 px) and cut out some regions for other things. I get an "Out of memory" exception when creating a new Bitmap instance:

using (FileStream fileStream = new FileStream(mapFileResized, FileMode.Open))
{
    byte[] data = new byte[fileStream.Length];
    fileStream.Read(data, 0, data.Length);
    using (MemoryStream memoryStream = new MemoryStream(data))
    {
        using (Bitmap src = new Bitmap(memoryStream)) // <-- exception
        {
            tile = new Bitmap(tileWidth, tileHeight, PixelFormat.Format24bppRgb);
            tile.SetResolution(src.HorizontalResolution, src.VerticalResolution);
            tile.MakeTransparent();
            using (Graphics grRect = Graphics.FromImage(tile))
            {
                grRect.CompositingQuality = CompositingQuality.HighQuality;
                grRect.SmoothingMode = SmoothingMode.HighQuality;
                grRect.DrawImage(
                        src,
                        new RectangleF(0, 0, tileWidth, tileHeight),
                        rTile,
                        GraphicsUnit.Pixel
                );
            }
        }
    }
}

When I use small image sizes (like 8000x4720 px), everything works fine.

How can I work with large images?

Tile PS. The bitmap is located in the finally block.

Regards, Alex.

+5
source share
3 answers

You use about a gigabyte of memory, not really surprising that you have run out of memory.

, 32- 16000x9440 , :

16000 * 9440 * (32/8) = ~ 576

byte[] data = new byte[fileStream.Length];
fileStream.Read(data, 0, data.Length);
using (MemoryStream memoryStream = new MemoryStream(data))
{
  [... snip ...]
}

, 576 .

[... snip ...]
    using (Bitmap src = new Bitmap(memoryStream)) // <-- exception
    {
        [... snip ...]
    }
[... snip ...]

, 576 ( , , 4, ). , .

, .

( , Google), , , .

+6
+3

MemoryStream , . , , , .

Since you apparently know how much data you need, you can highlight the correct size in front and thus avoid resizing.

However, as soon as you reach a certain size, you will run out of memory .. NET imposes a limit of 2 GB on one object ( even 64 bits ), so the internal array MemoryStreamcan never grow beyond this. If your image is larger, you will get a memory exception.

+2
source

All Articles