Proud Member
Proud Member

Reputation: 40496

How to obtain and modify a pixel value here?

Listing 2 of Apple's Q & A shows an example of how to modify pixels in a CGImageRef. The problem is: They're not showing how to obtain a pixel and modify it's R G B and A values.

The interesting part is here:

 void *data = CGBitmapContextGetData (cgctx);
    if (data != NULL)
    {

        // **** You have a pointer to the image data ****

        // **** Do stuff with the data here ****

    }

Now, lets say I want to read Red, Green, Blue and Alpha from pixel at x = 100, y = 50. How do I get access to that pixel and it's R, G, B and A components?

Upvotes: 1

Views: 217

Answers (1)

hotpaw2
hotpaw2

Reputation: 70703

First, you need to know the bytesPerRow of your bitmap, as well as the data type and color format of the pixels in your bitmap. bytesPerRow can be different from the width_in_pixels*bytesPerPixel, as there might be padding at the end of each line. The pixels can be 16-bits or 32-bits, or possibly some other size. The format of the pixels can be ARGB or BRGA, or some other format.

For 32-bit ARGB data:

unsigned char *p = (unsigned char *)bytes;
long int i = bytesPerRow * y + 4 * x;  // for 32-bit pixels
alpha = p[i  ];    // for ARGB 
red   = p[i+1];
green = p[i+2];
blue  = p[i+3];

Note that depending on your view transform, the Y axis might also appear to look upside down, depending on what you expect.

Upvotes: 3

Related Questions