No loadPixels() for PGraphicsPDF

i found this code Pointillism | Learning Processing 2nd Edition

but instead of run it on the screen, I wanted to run in 5 times on backend and save it as a pdf file,
and got this error
RuntimeException: No loadPixels() for PGraphicsPDF

here is the code I used:

import processing.pdf.*;


PImage img;
int pointillize = 16;

void setup() {
  //size(600,400);
  size(600,400,PDF,"f:\\process\\acres-01.pdf");
  img = loadImage("f:\\process\\acres-1.jpg");
  
  smooth();
}

void draw() {
  
  for (int loop = 0; loop<5; loop++)
  {
  background(0);
  
  for (int i=0; i<500; i++)
  
  {
      
  
  
  // Pick a random point
  int x = int(random(img.width));
  int y = int(random(img.height));
  int loc = x + y*img.width;

  // Look up the RGB color in the source image
  loadPixels();
  float r = red(img.pixels[loc]);
  float g = green(img.pixels[loc]);
  float b = blue(img.pixels[loc]);
  noStroke();

  // Draw an ellipse at that location with that color
  fill(r,g,b,100);
  ellipse(x,y,pointillize,pointillize);
  }
   PGraphicsPDF pdf = (PGraphicsPDF) g;  // Get the renderer
  
  //saveFrame("f:\\process\\ellipse-a-loop.png");
      pdf.nextPage();  // Tell it to go to the next page 
      
  }
  exit();
  
      
}

it won’t work because PDF is a vector file and it does not store pixels.

But in fact, I think the original code is wrong. loadPixels loads what is on the canvas window. Instead, you need to call img.loadPixels to specifically load pixels from the image.

Thanks for your reply.

As a matter of fact, I don’t need to save the imgae to the pdf.
I only want to save ellipses I create.

After I load all the pixels from the image, I no longer need it

I figured it out
I changes the loadPixels() to img.loadPixels as you suggested,
and moved it to the setup,

and it worked

Hello,

In this example you did not need loadPixels() or img.loadPixels (for the PImage) at all.

Try it!

There is a GitHub issue here that discusses the language in the references and tutorials:

:)