-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImageCache.java
More file actions
63 lines (58 loc) · 1.94 KB
/
Copy pathImageCache.java
File metadata and controls
63 lines (58 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* Authors: Jerry Li & Victor Jiang
* Date: June 13, 2025
* Description: This class stores and reuses images so the game doesn't have to load them from the disk repeatedly
*/
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.imageio.ImageIO;
/** Utility class that caches loaded images to avoid duplicate disk I/O. */
public final class ImageCache {
/**
* Cache of already loaded images. ConcurrentHashMap is used so that the
* cache can be accessed safely from multiple threads if image loading
* occurs on different game loops or Swing threads.
*/
public static final Map<String, BufferedImage> CACHE = new ConcurrentHashMap<>();
public ImageCache() {}
/**
* Loads an image from either the classpath or filesystem. Subsequent calls
* with the same path return the cached instance.
*/
public static BufferedImage load(String path) {
BufferedImage img = CACHE.get(path);
InputStream in = null;
InputStream fileIn = null;
InputStream auto = null;
if (img != null) {
return img;
}
try {
in = ImageCache.class.getResourceAsStream(path);
if (in != null) {
auto = in;
} else {
fileIn = new FileInputStream(new File(path));
auto = fileIn;
}
img = ImageIO.read(auto);
CACHE.put(path, img);
return img;
} catch (IOException e) {
System.err.println("Error loading image: " + path + " - " + e.getMessage());
return null;
} finally {
if (auto != null) {
try {
auto.close();
} catch (IOException ignored) {
}
}
}
}
}