简体   繁体   English

在Java中加载和缓存图像的最佳方法是什么?

[英]What is the best way to load and cache images in Java?

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. 我有一个超过一千个16乘16像素平铺图像的大集合,我需要用于Java制作的游戏。

What would be the best way to store the tiles without exhausting the available memory of the JVM? 在不耗尽JVM可用内存的情况下存储磁贴的最佳方法是什么?

I'm thinking that spawning 1000+ BufferedImages might not be wise... 我认为产生1000+ BufferedImages可能并不明智......

The main purpose for keeping the images at the ready is for loading maps, which will be dynamically spawned based on a map file. 保持图像准备就绪的主要目的是加载地图,这些地图将根据地图文件动态生成。

First, is loading all those images really a problem. 首先,加载所有这些图像真的是一个问题。 1000 images of 16 by 16 pixels are 256000 pixels. 16乘16像素的1000个图像是256000个像素。 Even when using 4 bytes for each pixel would result in just one MB of image data, which isn't much. 即使每个像素使用4个字节也只会导致1 MB的图像数据,这并不多。

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): 例如,如果你的游戏显示的是一个n × m图块的地图,你可以将n+2 m+2图块加载到内存中,或者直观地表示(其中*是可见的图块和+额外加载的图块到内存中):

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

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 当然,如果你的瓷砖相当小,或者移动地图的速度非常快,你可以增加你使用的额外瓷砖的数量

Have you tried? 你有没有尝试过? if you have 4 bytes per pixel, 16 x 16 x 4 x 1000 is about 1Mb + overhead. 如果每个像素有4个字节,则16 x 16 x 4 x 1000约为1Mb +开销。 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. 如果你负担不起,那么可能会创建更大的图像,加载它们然后根据需要提取出来。

I don't think buffering 1000+ images is best option, because it consumes lot of memory. 我不认为缓冲1000+图像是最好的选择,因为它消耗了大量的内存。 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. 也许最好是实现不同的逻辑,比如缓冲区,大多数使用的图像只有100左右(只需使用随机数,但你需要计算经常使用的图像数量),如果有任何图像比这些缓存,请在需要时加载它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM