What is the best way to upload and cache images in Java?

I have a large collection of more than one thousand 16 pixel images that I need for a game that I make in Java.

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

I think spawning 1000+ BufferedImages may be unreasonable ...

The main purpose of storing images in the finished form is to download maps, which will be dynamically generated based on the map file.

+4
source share
3 answers

Firstly, downloading all of these images is really a problem. 1000 images 16 by 16 pixels in size - 256,000 pixels. Even when using 4 bytes for each pixel, only one MB of image data is obtained, which is small.

If you really need / need to reduce the number of downloaded images in memory, you can only load the visual fragments / images needed for your card into memory and a few more to increase responsiveness for your game.

For example, if your game shows a map of n onto m tiles, you can load fragments of n+2 by m+2 into memory or visually display it (where * are visible tiles and + additional loading of the tile into memory):

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

When the user moves the map, you delete links to tiles that you no longer need, and start downloading new fragments. Since you have one tile in reserve in memory, moving the map should go pretty smoothly. Of course, if your tiles are quite small or moving the map fairly quickly, you can increase the number of extra tiles that you use.

+6
source

You tried? if you have 4 bytes per pixel, 16 x 16 x 4 x 1000 is about 1 MB + overhead. This is not so much. If you cannot afford it, then perhaps create large images, upload them and extract the fragments you need from them.

+1
source

I do not think that buffering 1000+ images is the best option because it consumes a lot of memory. It may be better to implement different logic, such as buffers, only the most used images, for example, 100 or so (just use a random number, but you need to determine how many frequently used images will be), if there is any image than these cached ones, loads them when necessary.

0
source

Source: https://habr.com/ru/post/1388506/


All Articles