Apologies for not getting something up sooner. It's a surprisingly tricky problem, but I've found a good solution and am now baking it into release 0144 since it's something that's used so often.
Until I post release 0144 (or for those using earlier releases), add the following method to your sketch:
Quote:
PImage loadImageAsync(String filename) {
PImage vessel = createImage(0, 0, ARGB);
AsyncImageLoader ail = new AsyncImageLoader(this, filename, vessel);
ail.start();
return vessel;
}
Next, create a new tab titled "AsyncImageLoader.java". And use this code:
Quote:
import processing.core.*;
public class AsyncImageLoader extends Thread {
static int loaderMax = 4;
static int loaderCount;
PApplet parent;
String filename;
PImage vessel;
public AsyncImageLoader(PApplet parent, String filename, PImage vessel) {
this.parent = parent;
this.filename = filename;
this.vessel = vessel;
}
public void run() {
while (loaderCount == loaderMax) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
loaderCount++;
PImage actual = parent.loadImage(filename);
if (actual == null) {
vessel.width = -1;
vessel.height = -1;
} else {
vessel.width = actual.width;
vessel.height = actual.height;
vessel.format = actual.format;
vessel.pixels = actual.pixels;
}
loaderCount--;
}
}
Now, when loading images, simply use loadImageAsync() instead of loadImage(). For instance:
Quote:
PImage bigImage;
void setup() {
bigImage = loadImageAsync("something.jpg");
}
void draw() {
if (bigImage.width == 0) {
// image is not yet loaded
} else if (bigImage.width == -1) {
// this means an error occurred during image loading
} else {
// image is ready to go, draw it
image(bigImage, 0, 0);
}
}
For 0144, I've also improved handling of OutOfMemoryErrors since that's so common with image loading. This will fix an increasingly common problem (especially on Mac OS X) that makes it look like an image that didn't load properly has halted the sketch.
(edit) It should also be noted that asynchronous image loading (particularly when downloading from a server) drastically improves performance. In my case it was a 2-3x speedup when downloading 20 JPEG files that were ~3 MB apiece.