views:

2123

answers:

3

I'm trying to write a greasemonkey script, and it would be preferable for it to be able to work with images (specifically, find the darkest pixel in an image). Is there a way to do this or must I embed flash?

+5  A: 

Since it's Firefox specific, you can use a canvas element. I've never written a greasemonkey script, so I don't know exactly how you would do it, but the idea is, you create a new canvas element and draw the image onto the canvas. Then, you can get the pixel values from the canvas.

// Create the canvas element
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;

// Draw the image onto the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);

// Get the pixel data
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

// Loop through imageData.data - an array with 4 values per pixel: red, green, blue, and alpha
for (int x = 0; x < imageData.width; x++) {
    for (int y = 0; y < imageData.height; y++) {
        var index = 4 * (y * imageData.width + x);
        var r = imageData.data[index];
        var g = imageData.data[index + 1];
        var b = imageData.data[index + 2];
        var a = imageData.data[index + 3];

        // Do whatever you need to do with the rgba values
    }
}
Matthew Crumley
A: 

Can I load an image that is on the page into the canvas? This looks promising, thank you.

Logan Serman
Yes. I guess I didn't explain that part very well. In the example code, "image" would be the img element from the page.
Matthew Crumley
I should also mention that, normally, getImageData only works when the image came from the same domain as the page. I don't know much about greasemonkey scripts, so I don't know if the same-origin policy applies or not.
Matthew Crumley
+1  A: 

Scrap the

var r = imageData.data[index];
var g = imageData.data[index + 1];
var b = imageData.data[index + 2];
var a = imageData.data[index + 3];

part, Javascript doesn't pass by reference.

hcalves