Image loading
authorNeil <neil@dip.sun.ac.za>
Tue, 6 Sep 2016 20:04:36 +0000 (22:04 +0200)
committerNeil <neil@dip.sun.ac.za>
Tue, 6 Sep 2016 20:05:51 +0000 (22:05 +0200)
tabakrolletjie/loader.py

index 7dad79aa6b00659521db851ce866cfd2895791aa..d37120fde77ed23431090626bb97b08f5679d96f 100644 (file)
@@ -3,12 +3,16 @@
 import json
 import os
 
+import pygame.image
+import pygame.display
+
 
 class Loader(object):
     """ Load data files from beneath a prefix. """
 
     def __init__(self, prefix):
         self._prefix = prefix
+        self._cache = {}
 
     def full_path(self, *parts):
         path = "/".join(parts)
@@ -24,6 +28,18 @@ class Loader(object):
         with self.open_file("stations", *parts) as f:
             return json.load(f)
 
+    def load_image(self, *parts):
+        """Return a pygame surface of the requested image."""
+        fn = self.full_path("images", *parts)
+        img = self._cache.get(fn, None)
+        if img is None:
+            img = pygame.image.load(fn)
+            # We assume pygame.display has been initialised
+            # Fix this if that changes
+            img.convert_alpha(pygame.display.get_surface())
+            self._cache[fn] = img
+        return img
+
 
 _DATA_PREFIX = os.path.abspath(
     os.path.join(os.path.dirname(__file__), "..", "data"))