Out of Memory when creating image using canvas

Project runs out of memory eventually after running for a while. (RuntimeException: java.lang.OutOfMemoryError: Java heap space)

I have narrowed down the issue to a particular snippet. Created a sketch with it that also runs out of memory:

void setup(){
  size(1000, 1000, P2D);
}

void draw(){
  PImage img = testImage(width,height);
  image(img, 0, 0);
  img = null;
}

PImage testImage(float _w, float _h){
    int w = floor(_w);
    int h = floor(_h);
    PGraphics canvas = createGraphics(w, h, P2D);

    canvas.beginDraw();

    PImage image = new PImage(w, h, RGB);

    //canvas.shader(shader);
    canvas.image(image, 0, 0);

    canvas.endDraw();

    return canvas;
}

Any clue what might be happening?
Thanks!

Managed to find a workaround that doesn’t cause memory leak:

void setup() {
  size(1000, 1000, P2D);
}

void draw() {
  PGraphics canvas = createGraphics(width, height);
  drawOnCanvas(canvas);
  image(canvas, 0, 0);
}

void drawOnCanvas(PGraphics _canvas) {
  _canvas.beginDraw();

  PImage image = new PImage(_canvas.width, _canvas.height, RGB);

  //_canvas.shader(shader);
  _canvas.image(image, 0, 0);

  image = null;

  _canvas.endDraw();

  _canvas = null;
}

But not sure why this works and the previous example does not :man_shrugging:

In the first example the canvas uses P2D (OpenGL) and in the second case it uses JAVA2D (Java AWT). I don’t know if this is the cause but it is the only significant difference that I can see.

3 Likes

Interestingly some years ago I had a P3D project that needed thousands of frame buffers and there was a memory leak after a while. I couldn’t solve the issue and I had to port some part of the code to openFrameworks and then I didn’t see the issue.

But @TellAJoke is there a reason why you need to create image and buffer every draw frame? Can’t you initialize it in setup and reuse it?

2 Likes

Sorry for the late reply.
I’m showcasing a series of different shaders at once. The shaders change over time too, so I’m creating new images every frame.