
It is really easy to load images into a processing sketch. Just keep in mind they will come in at their actual pixel size. The sketch below loads the above image using the PImage object. One thing to remember is that anything you load into your sketch should be placed in a folder named “data” in yor sketch folder.
//declare PImage object
PImage img;
void setup() {
size(900,675);
//load image
img = loadImage("romanescobroccoli.jpg");
}
void draw() {
//place image from rop left corner at 0,0 of the sketch
image(img, 0, 0);
}
You can sample the color data of each pixel in an image you have loaded. In the example above the image is being placed directly into the sketch and the sketch display is what is being sampled. In this case you don’t have the option of not showing the image in the sketch. The best way to sample an image whiteout showing it in the sketch to store it in a PGraphics object. This will allow you to sample the image without showing it in the sketch. The sketch below simply samples the image above and redraws it using points.
//declare PImage object
PImage img;
//declare PGraphics object to hold image
PGraphics image_holder;
int w = 900;
int h = 675;
void setup() {
size(900,675);
img = loadImage("romanescobroccoli.jpg");
image_holder = createGraphics(900, 675);
}
void draw() {
image_holder.beginDraw();
image_holder.image(img, 0, 0);
image_holder.endDraw();
for(int x = 0; x < w; x++){
for(int y = 0; y < h; y++){
color c = image_holder.get(x, y);
stroke(c);
point(x,y);
}
}
}
import controlP5.*;
ControlP5 cp5;
PImage img;
PGraphics image_holder;
int w = 900;
int h = 675;
int pixel_size = 5;
void setup() {
size(900,675);
img = loadImage("romanescobroccoli.jpg");
image_holder = createGraphics(900, 675);
cp5 = new ControlP5(this);
///declare a slider with a range of 0 - 1200
cp5.addSlider("pixel_size")
.setPosition(40,40)
.setRange(1,40)
.setSize(200,20)
.setValue(5)
.setColorForeground(color(150))
.setColorLabel(color(255))
.setColorBackground(color(70))
.setColorValue(color(0,0,0))
.setColorActive(color(200))
;
}
void draw() {
image_holder.beginDraw();
image_holder.image(img, 0, 0);
image_holder.endDraw();
for(int x = 0; x < w; x++){
for(int y = 0; y < h; y++){
if(x%pixel_size == 0 && y%pixel_size == 0){
color c = image_holder.get(x, y);
noStroke();
fill(c);
rect(x,y,pixel_size,pixel_size);
}
}
}
}