Before getting to useful examples, let's make a getPixel
function to obtain the color components of a point in the image and then complete a quick test case. The following steps will help you in this process:
Graphic
object next to the image. It's going to show a single color, so just make it big enough so that you can easily see the color. Name it swatch
.set the filled of graphic 1 to true
on mouseMove pMx,pMy --put getPixel(the short name of me,pMx - the left of me,pMy - the top of me) into tPixelColor --set the backgroundColor of graphic "swatch" to tPixelColor end mouseMove
getPixel
before we create that function!getPixel
function, which is very much like the one shown in the Image data format we discussed in the preceding steps:function getPixel pImage,pX,pY put the imageData of image pImage into tImageData put the width of image pImage into tWidth put ((pY-1)*tWidth + (pX-1)) * 4 into tStartChar put charToNum(char tStartChar+2 of tImageData) into tRed put charToNum(char tStartChar+3 of tImageData) into tGreen put charToNum(char tStartChar+4 of tImageData) into tBlue return tRed,tGreen,tBlue end getPixel
We made a very simple example case of how to use the color of a pixel in an image; in this case, how to colorize a swatch. As setting backgroundColor
of a graphic requires redvalue
, greenvalue
, and bluevalue
, we didn't need to convert the values from the image to a 24-bit number and the getPixel
function was able to return tRed,tGreen,tBlue
.
Now, there isn't really any advantage to the way we did that compared to the built-in mouseColor
function. However, at least we gave the getPixel
function a tryout!
Bytes was mentioned a few times in this chapter and you may well know about bit depth as we've talked about digital photographs. So tell me, how many bits are there in a byte?
Answer: 8
We won't even talk about bits or bytes in the rest of this chapter; however, if only for the interest to mathematicians, it's good to know that a byte is 8 bits. A bit is a binary digit, and when you start to think of bits in those terms, you will see that a byte can store 2 to the power of 8 values in it (binary being Base 2). This comes into play when you look at the length of a Pascal string (2 to the power of 8 is 256, hence the range of characters in a Pascal String is 0-255) and it helps you realize that if a picture is made up of one byte, for each pixel's red, green, and blue values, it's a 24-bit picture. Once you add in another byte of data for the alpha channel, you have a 32-bit picture.
In some applications, you need to know exactly which area of an image the user is pointing at. For example, when there is a map and you want to show information related to the region the user has clicked on, this could be done using a lot of rectangular buttons or you could break the regions into graphics and use a mouseEnter
handler to detect which region it is. Instead, you could use a single image to represent all the regions.