Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

59
LINES

< > BotCompany Repo | #1035949 // ThumbnailCache

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (11661L/67K).

1  
transient sclass ThumbnailCache {
2  
  settable WidthAndHeightImpl thumbnailSize = new(100);
3  
  
4  
  // max bytes in memory
5  
  settable long maxBytes = oneMegabyte();
6  
  
7  
  // estimated bytes in memory
8  
  gettable long usedBytes;
9  
  
10  
  Q q = startQ();
11  
  
12  
  new TheMap map;
13  
  
14  
  transient Lock lock = lock();
15  
  
16  
  class TheMap extends LinkedHashMap<File, BufferedImage> {
17  
    @Override
18  
    protected bool removeEldestEntry(Map.Entry<File, BufferedImage> eldest) {
19  
      if (usedBytes > maxBytes) {
20  
        usedBytes -= guessImageBytes(eldest.getValue());
21  
        true;
22  
      }
23  
      false;
24  
    }
25  
  }
26  
  
27  
  int guessImageBytes(BufferedImage image) {
28  
    // 24 is a random guess for the overhead of an image
29  
    ret 24+guessImageSizeInMemory(image);
30  
  }
31  
  
32  
  BufferedImage makeThumbnail(File file) {
33  
    var fullSize = loadImage2(file);
34  
    ret scaleBufferedImageToMaxWidthOrHeight(thumbnailSize, fullSize);
35  
  }
36  
  
37  
  selfType thumbnailSize(int wAndH) {
38  
    ret thumbnailSize(new WidthAndHeightImpl(wAndH));
39  
  }
40  
  
41  
  void get(File imageFile, IVF1<BufferedImage> onLoad) {
42  
    lock lock;
43  
    if (map.containsKey(imageFile))
44  
      onLoad.get(map.get(imageFile));
45  
    else
46  
      q.add(-> {
47  
        BufferedImage img = null;
48  
        pcall {
49  
          img = makeThumbnail(imageFile);
50  
        }
51  
        {
52  
          lock lock;
53  
          usedBytes += guessImageBytes(img);
54  
          map.put(imageFile, img);
55  
        }
56  
        onLoad.get(img);
57  
      });
58  
  }
59  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): elmgxqgtpvxh, mqqgnosmbjvj, wnsclhtenguj

No comments. add comment

Snippet ID: #1035949
Snippet name: ThumbnailCache
Eternal ID of this version: #1035949/14
Text MD5: acb9dd604e9998eb74ac5cf73c1df9e2
Transpilation MD5: ef5a9db2c6916fefa0c87fe02fe8c288
Author: stefan
Category: javax / io
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-08-17 21:51:28
Source code size: 1493 bytes / 59 lines
Pitched / IR pitched: No / No
Views / Downloads: 147 / 255
Version history: 13 change(s)
Referenced in: [show references]