1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
6 import org.xwt.translators.*;
9 * The in-memory representation of a PNG or GIF image. It is
10 * read-only. It is usually passed to PixelBuffer.drawPicture()
12 * Implementations of the Platform class should return objects
13 * supporting this interface from the createPicture() method. These
14 * implementations may choose to implement caching strategies (for
15 * example, using a Pixmap on X11).
17 public class Picture {
19 public Picture() { this.res = null; }
20 public Picture(Stream r) { this.res = r; }
21 private static Cache cache = new Cache(100); ///< Picture, keyed by the Stream that loaded them
23 public Stream res = null; ///< the resource we were loaded from
24 public int width = -1; ///< the width of the image
25 public int height = -1; ///< the height of the image
26 public int[] data = null; ///< argb samples
27 public boolean isLoaded = false; ///< true iff the image is fully loaded
29 /** turns a resource into a Picture.Source and passes it to the callback */
30 public static Picture load(final Stream r, final Scheduler.Task callback) {
31 Picture ret = (Picture)cache.get(r);
32 if (ret == null) cache.put(r, ret = Platform.createPicture(r));
33 final Picture p = ret;
34 if (!ret.isLoaded && callback != null)
35 new java.lang.Thread() { public void run() {
36 // get the InputStream for the image
37 InputStream in = null;
39 in = r.getInputStream();
40 } catch (IOException e) {
42 if (r instanceof Stream.Ref) {
43 // add extensions to the resource, looking for the image
44 Stream.Ref ref = (Stream.Ref)r;
47 String[] exts = new String[] { ".png", ".jpeg", ".gif" };
48 for (int i=0; i < exts.length && in == null; i++) {
49 newr = ref.addExtension(exts[i]);
50 try { in = newr.getInputStream(); }
51 catch (IOException f) { in = null; }
56 // could not find image
57 if (in == null) { Log.info(Picture.class, "couldn't load image for resource " + r); return; }
60 PushbackInputStream pbis = new PushbackInputStream(in);
61 int firstByte = pbis.read();
62 if (firstByte == -1) throw new JSExn("empty stream reading image");
63 pbis.unread(firstByte);
64 if ((firstByte & 0xff) == 'G') GIF.load(pbis, p);
65 else if ((firstByte & 0xff) == 137) PNG.load(pbis, p);
66 else if ((firstByte & 0xff) == 0xff) Platform.decodeJPEG(pbis, p);
67 else throw new JSExn("couldn't figure out image type from first byte");
69 Scheduler.add(callback);
70 } catch (Exception e) {
71 Log.info(this, "exception while loading image");