März 5, 2012
A simple color fetcher.PImage img; int w, h; void setup() { w = 50; h = 50; size(800, 600); img = loadImage("ducks.jpg"); } void draw() { background(0); image(img, 0, 0); fill(getAverageColor(img, mouseX, mouseY, w, h)); rect(mouseX, mouseY, w, h); //img.updatePixels(); } color getAverageColor(PImage img, int posX, int posY, int w, int h) { float rA, gA, bA, r, g, b; rA=0; gA=0; bA=0; float rangeH, rangeW; rangeH=posY+h; if (rangeH >height) rangeH = height; rangeW=posX+w; if (rangeW >width) rangeW = width; for (int y = posY; y < rangeH; y++ ) { for (int x = posX; x < rangeW; x++ ) { int loc = x + y*width; r = red(img.pixels [loc]); g = green(img.pixels[loc]); b = blue(img.pixels[loc]); rA+=r; gA+=g; bA+=b; } } rA=rA/(w*h); gA=gA/(w*h); bA=bA/(w*h); return color(rA, gA, bA); }