s it possible to access or set individual pixels of an image?
Trevor DeVore
lists at mangomultimedia.com
Wed Nov 17 08:23:10 EST 2010
On Tue, Nov 16, 2010 at 6:50 PM, Marty Billingsley
<marty at ucls.uchicago.edu>wrote:
> Is it possible to read and set the color of individual pixels in an image?
> ImageData is a little incomprehensible.
>
> Basically, I'd like to be able to do something like:
> for each pixel in image "x", set the color of that pixel to some
> calculated value (or a value pulled from a pixel of another image)
>
> Thanks for any pointers you can give me!
>
Unfortunately there is no shortcut for looping over each pixel. It would be
great to be able to do this:
repeat with i = 1 to the number of pixels of theImageData
put pixel i of theImageData into thePixelA
put 20 into thePixelA["red"]
put 0 into thePixelA["green"]
put 255 into thePixelA["blue"]
set pixel i of theImageData to thePixelA
end repeat
But we can't :-)
You will need to work with the imageData. It isn't too bad once you get your
head around it. Here is one way you could loop through the imageData of an
image, accessing individual pixels. This may not be the most efficient way
but hopefully it illustrates how to access each pixel clearly enough so that
the format of the imageData makes sense.
put the imageData of img 1 into theImageBytes
repeat with i = 1 to the number of bytes of theImageBytes
put byte i of theImageBytes into theAlphaValue -- always 0
put byte (i+1) of theImageBytes into theRedValue
put byte (i+2) of theImageBytes into theGreenValue
put byte (i+3) of theImageBytes into theBlueValue
## Convert bytes to numbers that you can manipulate
put charToNum(theRedValue) into theRedValue
put charToNum(theGreenValue) into theGreenValue
put charToNum(theBlueValue) into theBlueValue
## manipulate values as needed
...
## Convert back into binary data
put numToChar(theRedValue) into theRedValue
put numToChar(theGreenValue) into theGreenValue
put numToChar(theBlueValue) into theBlueValue
## Store modified pixel in theImageBytes
put theRedValue into byte (i+1) of theImageBytes
put theGreenValue into byte (i+2) of theImageBytes
put theBlueValue into byte (i+3) of theImageBytes
## You might be tempted to use "step 4" in the repeat loop up above.
## The problem with this is that the engine will execute one last time
when
## the counter steps to (the number of bytes + 1). This is no good as
there
## will be no pixel starting at (the number of bytes + 1).
## Instead, we rely on the repeat loop incrementing i by 1 and we add on
an
## additional 3 for the equivalent of "step 4"
add 3 to i
end repeat
set the imageData of img 1 to theImageBytes
Hopefully this helps.
--
Trevor DeVore
Blue Mango Learning Systems
ScreenSteps: http://www.screensteps.com
Releasable Revolution Resources for Developers:
http://revolution.bluemangolearning.com
More information about the use-livecode
mailing list