Render sketch to images

Using the saveFrame fonction on Keypressed
https://processing.org/reference/saveFrame_.html

import processing.video.*;
import processing.pdf.*;

Capture cam;

int nb_seconds, nb_images;
int nFrames = 3;
int nDisplay = 0;

boolean record;

void setup() {
  size(1800, 400);
  cam = new Capture(this, 640,480,30);
  cam.start();
  // draw() will execute 1 time per second
  frameRate(1);
}

void draw() {
  if(cam.available()){
    nb_seconds++;
    if (nb_seconds%3 == 0) {
      // this will execute every 3 seconds
      nb_images++;
      cam.read();
      PImage pg = cam.get();
      pg.save("image_" + nb_images + ".png");
      image(cam, nDisplay,0);
      if(nDisplay >= width){
        nDisplay = 0;
      }
      else{
        nDisplay += (width/nFrames);
      }
    }
  }
} 

void keyPressed(){
  saveFrame("frame-######.jpg");
}