root/InOutExpositor/ImageLoader.pde

Revision cb5297d42f18823d3b05ce472cd6328700f52241, 1.5 kB (checked in by Robin Gareus <robin@…>, 11 months ago)

load images in background.

  • Property mode set to 100644
Line 
1// http://processing.org/discourse/yabb2/YaBB.pl?board=Integrate;action=display;num=1204990614
2
3class ImageLoader implements Runnable {
4  ImageURL img[];
5
6  public ImageLoader() {
7    img=new ImageURL[100];
8  }
9
10  public int loadImg(String _url) {
11          int i;
12                for (i=0; i< 100; ++i) {
13                  if (img[i] == null) {
14        img[i]=new ImageURL(_url);
15                          return i;
16                        }
17                }
18    println("Image Loader: request queue overflow.");
19    // expand array if necessary
20    //if(num==img.length) img=(ImageURL[])expand(img);
21                return -1;
22  }   
23
24  public PImage getImage(int id) {
25    if(img[id]==null || !img[id].loaded || img[id].error)
26                        return null;
27    return img[id].img;
28  }
29
30  public void delImage(int id) {
31    img[id]=null;
32        }
33
34  public void run() {
35    while(true) {
36                        int i;
37                        for (i=0; i<100; ++i) {
38                    if (img[i] != null
39                                    && img[i].url != ""
40                                    && img[i].loaded == false
41                                    && img[i].error  == false
42                                        ) {
43                                        print("Image Loader: request id:"+i+"\n");
44                                        img[i].load(); // load image
45                                }
46                        }
47                        try {
48                                loadThread.sleep(500);
49                        } catch(InterruptedException e) {
50                                e.printStackTrace();
51                        }
52    }
53  }
54}
55
56class ImageURL {
57  PImage img;
58  boolean loaded=false,error=false;
59  String url="";
60
61  public ImageURL(String _url) {
62    url=_url;
63  }
64
65  void load() {
66    println("nLoading image: "+url);
67    img=loadImage(url);
68    if(img==null) error=true;
69    loaded=true;
70    if(error) println("Error occurred when loading image.");
71    else println("Load successful. "+
72    "Image size is "+img.width+"x"+img.height+".");
73  }
74}
Note: See TracBrowser for help on using the browser.