C#位图映像在运行时使用大量RAM



我今天做了一个TILEMAP发电机,我注意到,当导入大小128x128像素的图像时,将它们拼接在一起(TileMap)将其拼接在一起,将其拼接到一个大型位图中(8192x8192250MB RAM当图像输出到磁盘(BinaryWriter)仅为400KB。我不明白为什么它在内部使用这么多RAM。

default_tile_size = 128default_size = 8192

这是这里的代码:

public static Bitmap GenerateTileMapFromDirectory(string path, int tileSize = DEFAULT_TILE_SIZE)
{
    if (!Directory.Exists(path)) throw new DirectoryNotFoundException();
    Bitmap bmp = new Bitmap(DEFAULT_SIZE, DEFAULT_SIZE);
    int x = 0, y = 0;
    foreach (string file in Directory.GetFiles(path))
    {
        string ext = Path.GetExtension(file);
        if (ext.ToLower() == ".png")
        {
            Bitmap src = (Bitmap)Bitmap.FromFile(file);
            if (src.Width != tileSize || src.Height != tileSize)
            {
                //Log that PNG was not correct size, but resize it to fit constraints...
                Console.WriteLine(Path.GetFileName(file) + " has incorrect size ... Resizing to fit");
                src = new Bitmap(src, tileSize, tileSize);
            }
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
            {
                g.DrawImage(src, x, y, tileSize, tileSize);
            }
            src = null;
        }
        else
        {
            Console.WriteLine(Path.GetFileName(file) + " is not a PNG ... Ignoring");
            continue;
        }
        if (x < bmp.Width) x += tileSize;
        if (x == bmp.Width)
        {
            x = 0;
            y += tileSize;
        }
        if (y == bmp.Height) break;
    }

    //For generation verification, uncomment the following two lines.
    //if (File.Exists("D:\output.png")) File.Delete("D:\output.png");
    //if (bmp!=null) bmp.Save("D:\output.png");
    return bmp;
}

您创建的位图是8192 x 8192,并且在写入磁盘之前都在内存中。位图中的每个像素都需要4个字节(红色,绿色,蓝色,alpha)。因此,所需的内存(RAM)为8192 x 8192 x 4字节= 256mb。

写入磁盘时,您可能正在以PNG格式保存它,该格式使用无损耗的压缩来减少文件大小。

ps-正如Matthew在评论中指出的那样,您还应该用"使用"或正确处理SRC位图。

我也会一次又一次地使用图形,而不是每个图形。

最新更新