[SOLVED] PGraphics.image gives NullPointerException

I created a sketch with a PImage that I was then going to draw into a PGraphics using PGraphics.image() – but I got a NullPointerException.

Why is this happening?

I have created an MCVE below to demonstrate the problem on Processing 3.4:

PImage img;
PGraphics pg;

void setup() {
  img = loadImage("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Processing_3_logo.png/240px-Processing_3_logo.png");
  pg = createGraphics(240, 240);
  pg.image(img, 0, 0);  // NullPointerException
}

void draw(){
  image(pg, 0, 0);
  noLoop();
}
2 Likes

Sigh. So simple – I forgot to call beginDraw() / endDraw() before and after pg.image(), so it wasn’t accessing pixels[] correctly to draw.

The PImage and PGraphics both existed, but beginDraw “should be called before anything is drawn into the object.”

https://processing.org/reference/PGraphics_beginDraw_.html

I periodically forget this when I haven’t used a PGraphics in a while – just like I periodically forget about loadPixels.

Sad trombone.

But problem solved.

3 Likes