View Javadoc

1   /*
2    *******************************************************************************
3    * Copyright (c) 2005 Chris Rose and AIMedia
4    * All rights reserved. ImageFactory and the accompanying materials
5    * are made available under the terms of the Common Public License v1.0
6    * which accompanies this distribution, and is available at
7    * http://www.eclipse.org/legal/cpl-v10.html
8    * 
9    * Contributors:
10   *     Chris Rose
11   *******************************************************************************/
12  package ca.spaz.util;
13  
14  import java.awt.*;
15  import java.net.URL;
16  import java.util.*;
17  
18  import ca.spaz.cron.CRONConfiguration;
19  
20  /***
21   * A class for manufacturing images from the resource path. 
22   * @author Chris Rose
23   */
24  public class ImageFactory {
25  
26     private static ImageFactory instance = null;
27     private int cacheSize;
28     private Map imageCache;
29     
30     private ImageFactory() {
31        String cacheValue = CRONConfiguration.getInstance().getProperty("cron.imagecache.size", "10");
32        int cacheSz = 0;
33        try {
34           cacheSz = Integer.parseInt(cacheValue);
35        } catch (NumberFormatException e) {
36           cacheSz = 10;
37           e.printStackTrace();
38        }
39        this.cacheSize = cacheSz;
40        this.imageCache = new CacheMap(cacheSize);
41     }
42     
43     public static final ImageFactory getInstance() {
44        if (null == instance) {
45           instance = new ImageFactory();
46        }
47        return instance;
48     }
49     
50     public Image loadImage(URL url) {
51        Image ret = null;
52        if (imageCache.containsKey(url)) {
53           ret = (Image) imageCache.get(url);
54        } else {
55           ret = Toolkit.getDefaultToolkit().createImage(url);
56           if (ret != null) {
57              imageCache.put(url, ret);
58           }
59        }
60        return ret;
61     }
62     
63     public Image loadImage(String resourceID) {
64        return loadImage(resourceID, this); 
65     }
66     
67     public Image loadImage(String resourceID, Object source) {
68        Class base = null;
69        if (null == source) {
70           base = this.getClass();
71        } else {
72           base = source.getClass();
73        }
74        URL url = base.getResource(resourceID);
75        Image ret = null;
76        if (url == null) {
77           url = this.getClass().getResource(resourceID);
78           if (url == null) {
79              throw new IllegalArgumentException(resourceID + " is not a valid resource identifier");
80           }
81        }
82        ret = loadImage(url);
83        return ret;
84     }
85     
86  }