What is the best way to load and cache images in J

2019-05-09 08:10发布

I have a large collection of over one thousand 16 by 16 pixel tile images that I'll need for a game I'm making in Java.

What would be the best way to store the tiles without exhausting the available memory of the JVM?

I'm thinking that spawning 1000+ BufferedImages might not be wise...

The main purpose for keeping the images at the ready is for loading maps, which will be dynamically spawned based on a map file.

3条回答
一纸荒年 Trace。
2楼-- · 2019-05-09 08:29

Have you tried? if you have 4 bytes per pixel, 16 x 16 x 4 x 1000 is about 1Mb + overhead. That's not that much any more. If you can't afford that, then maybe create larger images, load those and then extract the tiles out as you need them.

查看更多
看我几分像从前
3楼-- · 2019-05-09 08:32

I don't think buffering 1000+ images is best option, because it consumes lot of memory. May be it is better to implement different logic like buffer only most used images like 100 or so (just used random number, but you need to figure how many frequent used images will be), if any image than these cached, load them when required.

查看更多
SAY GOODBYE
4楼-- · 2019-05-09 08:53

First, is loading all those images really a problem. 1000 images of 16 by 16 pixels are 256000 pixels. Even when using 4 bytes for each pixel would result in just one MB of image data, which isn't much.

If you really want/need to reduce the number of images you load into memory, you could only load the visual tiles/images needed for your map into memory, and a few more to increase responsiveness for your game.

For example if your game shows a map of n by m tiles, you could load a n+2 by m+2 tiles into memory, or visually represented (where * are visible tiles and + the extra loaded tiles into memory):

+++++++++++
+*********+
+*********+
+*********+
+++++++++++

When the user moves the map, you remove the references to the tiles you no longer need and start loading the new tiles. Since you have one tile in reserve in memory, moving the map should still happen quite smoothly. Of course, if your tiles are rather small, or moving the map happens pretty fast you can increase the number of extra tiles you use

查看更多
登录 后发表回答