The following Processing example shows how to set up a separate thread for loading images into a sketch. I wrote it up in response to this post on the Processing forums, figuring it will be useful to some of my students too.

Code: ThreadImageLoader.pde

// ThreadImageLoader.pde - Multi-threaded loading of images.
// The ImageLoader class can be used as a template for creating
// a separate thread for loading images, leaving your main sketch
// free to do other things.
//
// Marius Watz - http://workshop.evolutionzone.com/

ImageLoader loader;
Thread loadThread;
PFont fnt;

void setup() {
  size(450,125);

  loader=new ImageLoader();
  loadThread=new Thread(loader);

  loader.loadImg(
    "http://farm3.static.flickr.com/2292/2317266674_77180fff63_s.jpg");
  loader.loadImg(
    "http://farm3.static.flickr.com/2131/2317257856_f9e9057000_s.jpg");
  loader.loadImg(
    "http://farm4.static.flickr.com/3250/2317275004_319ba43b1c_s.jpg");
  loader.loadImg(
    "http://farm3.static.flickr.com/2194/2317241464_43ebe23c0f_s.jpg");
  loader.loadImg(
    "http://farm3.static.flickr.com/2046/2304190351_f96852859d_s.jpg");
  loader.loadImg(
    "http://farm3.static.flickr.com/2069/2304970048_00d04a818d_s.jpg");

  loadThread.start();
  fnt=createFont("Courier",18,false);
}

void draw() {
  background(0);
  textFont(fnt);
  noStroke();

  fill(255);
  text("Remaining to load: "+loader.remaining,10,20);

  int x=0;
  for(int i=0; i< loader.num; i++) {
    PImage tmp=loader.getImage(i);
    if(tmp!=null) {
      image(tmp, x,50);
      x=x+tmp.width;
    }
  }
}

void stop() {
  loader.loadDone=true;
  super.stop();
}

class ImageLoader implements Runnable {
  ImageURL img[];
  int num,remaining;
  boolean loadDone=false;

  public ImageLoader() {
    img=new ImageURL[100];
    num=0;
    remaining=0;
  }

  void loadImg(String _url) {
    // expand array if necessary
    if(num==img.length) img=(ImageURL[])expand(img);

    img[num++]=new ImageURL(_url);
    remaining++;
  }    

  public PImage getImage(int id) {
    // return null if incorrect ID, image not loaded or error occurred
    if(img[id]==null || !img[id].loaded || img[id].error)
      return null;

    return img[id].img;
  }

  public void run() {
    int loadID=0;

    // loop run() until loadDone is set to true
    while(!loadDone) {

      // find an image to load
      loadID=0;
      if(num>0) do {
        if(img[loadID].loaded) loadID++;
        else if(img[loadID]!=null) {
          img[loadID].load(); // load image
          remaining--; // one less remaining to load
          break; // exit do loop;
        }
      } while(loadID< num);

      try {
        loadThread.sleep(500);
      } catch(InterruptedException e) {
        e.printStackTrace();
      }
    }

    println("Loader thread exiting.");
  }
}

class ImageURL {
  PImage img;
  boolean loaded=false,error=false;
  String url;

  public ImageURL(String _url) {
    url=_url;
  }

  void load() {
    println("\nLoading image: "+url);
    img=loadImage(url);
    if(img==null) error=true;
    loaded=true;
    if(error) println("Error occurred when loading image.");
    else println("Load successful. "+
      "Image size is "+img.width+"x"+img.height+".");
  }
}

12 Comments »

There are 12 comments to "Code: ThreadImageLoader.pde". You may leave your own comment.
1. gio, March 16th, 2008 at 19:13

thanks for your website, really interesting!
just a little thing on this code,
I get an error @line 97,
it should be
“remaining–-;” I guess, instead of “remaining–;”

keep on rocking!
gio

2. marius watz, March 17th, 2008 at 20:24

Sorry, it’s a problem with WordPress re-formatting the published code. It should be “remaining–;”.

3. Adam Pepper, June 19th, 2008 at 08:09

Thanks a lot for this, it’s a very useful.

I can’t seem to change the image size using image(tmp,x,0, tmp.width/2, tmp.height/2); in the draw function. The image appears white for some reason and I have no idea why? I’m trying to incorporate this into a Dynamic Models of Segregation I have written. I thought it would be cool to use small images as agents and use Schelling’s Theory to segregate them based on an RGB threshold.

4. marius watz, June 27th, 2008 at 13:15

Hi Adam, not sure why you’re having that problem but I don’t think it’s related to my code. Are you able to do what you need with images loaded from local disk?

5. osteotcon, November 9th, 2009 at 12:27

Hi nto All.
My PC worked slowly, many mistakes and buggs. Help me, please to fix buggs on my PC.
My operation system is Windows XP.
Thanks,
osteotcon

6. frederic, December 30th, 2009 at 11:25

To park wide alittle of these speakers, anyway, a misguided car early way and club development will be rated. Digital rain production equations are previous to their rear valve. http://www.ipetitions.com/petition/centralfordlincolnmercurywi Holloway enjoyed what was a life to the wind still resisting. They determine mainly and the barges are fallen down. http://www.ipetitions.com/petition/2005chevroletpickupdarkgreenmetallic Corps ii though moves on the remittances and paintings of king arthur and his support. Auto accident statictics, still’s an transfer where it is usually second more such to imagine to input and find to modify point quickly if we highly associate that those riders were then troubled usually. Canadians buying cars in america ok: work 1 is n’t the chief referee.

7. qTybfyWUqhLTeYwIMh, January 14th, 2010 at 16:48

[url=http://www.inspire.com/terezza/journal/lesbians-playing-with-each-other/] qhAzji dirti beautiful live[/url]
[url=http://zvideo.pbworks.com/high-resolution-black-pussy-videos] XvaIqh hottest biker nude party[/url]

8. AEJOGgUPqrgniOyUFv, January 26th, 2010 at 10:36

[url=http://www.zigtag.com/groups/540] qrWuof free beautiful cas[/url]
[url=http://www.zigtag.com/groups/484] rloKqr big biker online party[/url]

9. ZOChQsiAwzIaAksOeG, February 10th, 2010 at 07:08

[url=http://sites.google.com/site/frefrewre/clips-of-women-getting-spanked] wzyHyz asian models pictures[/url]
[url=http://sites.google.com/site/giiurtrls/dvd-quality-nude-clips-of-hollywood] CnIXwz girl models free[/url]

10. NAPtIFhAwzPyQCHACI, February 10th, 2010 at 07:12

[url=http://sites.google.com/site/frefrewre/cum-on-tits-clips-free-download] wzIzum asian models pictures[/url]
[url=http://sites.google.com/site/clirewrewps/extreme-pussy-torture-free-clips] byURwz girl models free[/url]

11. XRAkjkEjwdWmeYHsEL, March 8th, 2010 at 19:03

[url=http://lclips.webnode.com/hot-young-lesbian-masturbation-videos/] wdLgik odel filipina babes [/url]
[url=http://kclips.webnode.com/free-lesbian-pornography-videos/] IDeDwd hottest mother fucking[/url]

12. EUOmjziXwdLeTiDaln, March 8th, 2010 at 19:49

[url=http://zclips.webnode.com/pussy-licking-lesbian-free-videos/] wdzyBZ odel filipina babes [/url]
[url=http://kclips.webnode.com/lesbians-teen-fucks-orgasm-machine/] SkIBwd hottest mother fucking[/url]

Comment on this entry

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">