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
2008-12-14 04:07:42
A:
Can I load an image that is on the page into the canvas? This looks promising, thank you.
Logan Serman
2008-12-14 04:53:17
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
2008-12-14 05:11:15
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
2008-12-14 05:13:07
+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
2009-07-13 03:02:13