Working with Pixels from Images

Use img.get(x, y) to get a pixel from an image. The result is a color (not an image). Normally, x and y should be integers (just like an array index), but it is not necessary. I think non-integer locations are interpolated colors from surrounding pixels, but I’m not sure.

Here’s a program to display the color under the mouse cursor. Note that since the image is offset and scaled by gScale, we have to do the inverse mapping to find the pixel under the mouse. E.g. if the mouse is at (10, 10) we want that to be pixel (0, 0). Since the image size is multiplied by gScale to get canvas coordinates, we need to divide the mouse location (also in canvas coordinates) to get to the corresponding image coordinates.


var gScale = 0.3;
var img;

function preload() {
    img = loadImage("");

function setup() {
    createCanvas(400, 400);

function draw() {
    image(img, 10, 10,
          img.width * gScale, img.height * gScale);
    // constrain is used so that x, y will be within the image
    var x = constrain((mouseX - 10) / gScale, 0, img.width - 1);
    var y = constrain((mouseY - 10) / gScale, 0, img.height - 1);
    // get the color at x, y
    var c = img.get(x, y);

    // draw a big circle filled with the color at x, y
    ellipse(mouseX, mouseY, 40, 40);