JosRego
JosRego

Reputation: 51

can't get pixels[] from an PImage in processing js

i've been trying to run the following code using processing.js however it just gets me a grey window. I think it's because its not accessing correctly to the image pixels[].

PImage img;


void setup() {  // this is run once.  
 size(600, 400); 
 img=loadImage("http://c.tadst.com/gfx/600x400/int-mountain-day.jpg?1");

} 
void draw() {  // this is run repeatedly.   

int dimension = (img.width*img.height);
img.loadPixels();
for (int i=0; i < dimension; i+=2) { 
  img.pixels[i] = color(0, 0, 0); 
} 
img.updatePixels();
   image(img, 0, 0);
}

the code is running here http://sketchpad.cc/sp/pad/view/ro.TExeW6NhoU8/rev.163

Upvotes: 2

Views: 890

Answers (2)

Allen
Allen

Reputation: 490

I've been dealing with this very issue. The problem appears to be that the documentation is just flat out wrong.

I was doing almost exactly what you show above with the same result, but it turns out that this is the way you have to do it:

var pixels = bg.pixels.toArray();
for(var i=0;i<pixels.length;++i){
  pixels[i] = color(0);
}
bg.pixels.set(pixels);

JSFiddle

Upvotes: 0

andreugrimalt
andreugrimalt

Reputation: 31

I don't know exactly why it doesn't work on processing.js.

However, you are doing the image processing (drawing the black stripes) each time the draw() function is called, this seems unnecessary and might be too intensive for the browser. Remember that the setup() function gets called once when the sketch starts whereas the draw() function gets called in an infinite loop while the sketch is running (it stops when you close the sketch).

So basically do the image processing once in the setup() function and then draw the processed image in the draw() function (you don't need to, you could draw the image also in the setup() function). Looking at your other examples at http://sketchpad.cc/sp/pad/view/ro.TExeW6NhoU8/rev.163 this code might do:

PImage img;

void setup() {  // this is run once.  
  size(600, 400); 
  img=loadImage("http://c.tadst.com/gfx/600x400/int-mountain-day.jpg?1");
  img.loadPixels();
  int dimension = (img.width*img.height);
  for (int i=0; i < dimension; i+=2) { 
     img.pixels[i] = color(0, 0, 0);
  } 
  img.updatePixels();
} 
void draw() {  // this is run repeatedly. It only draws the image again and again.   
  image(img, 0, 0);
}

Upvotes: 0

Related Questions