0

I'm using a UIImage category method from this tutorial to get the color of a specific pixel within a UIImage, based on the position of a tap. It's a grayscale image, and fully opaque. I've copied the method here:

- (UIColor *)colorAtPoint:(CGPoint)pixelPoint {
    if (pixelPoint.x > self.size.width || pixelPoint.y > self.size.height) {
        return nil;
    }

    CGDataProviderRef provider = CGImageGetDataProvider(self.CGImage);
    CFDataRef pixelData = CGDataProviderCopyData(provider);
    const UInt8* data = CFDataGetBytePtr(pixelData);

    int numberOfColorComponents = 4;
    float x = pixelPoint.x;
    float y = pixelPoint.y;
    float w = self.size.width;
    int pixelInfo = ((w * y) + x) * numberOfColorComponents;

    UInt8 red = data[pixelInfo];  // <--- CRASH, if tapped in lower 2/3 of image
    UInt8 green = data[(pixelInfo + 1)];
    UInt8 blue = data[pixelInfo + 2];
    UInt8 alpha = data[pixelInfo + 3];
    CFRelease(pixelData);

    // RGBA values range from 0 to 255
    return [UIColor colorWithRed:red/255.0
                           green:green/255.0
                            blue:blue/255.0
                           alpha:alpha/255.0];
}

When I tap within the top third of the image, it works perfectly. But when I tap in the lower two-thirds (or so) of the image, it crashes every time on that UInt8 red line I noted above. Nothing appears in the log, but I get a red EXC_BAD_ACCESS warning at that line.

Can anyone help me understand what might be going wrong, and how I can fix it?

EDIT: Logging the data and pixelInfo values from a series of taps doesn't seem to provide any useful info:

 NSLog(@"Data: %d, PixelInfo: %d", data, pixelInfo);

Results:
 Data: 134430720, PixelInfo: 594858
 Data: 134430720, PixelInfo: 650668
 Data: 134430720, PixelInfo: 688389
 Data: 134430720, PixelInfo: 633472
 Data: 134430720, PixelInfo: 597113
 Data: 134430720, PixelInfo: 579214
 Data: 134430720, PixelInfo: 856866
 Data: 134430720, PixelInfo: 1060593
 Data: 134430720, PixelInfo: 1130469
 Data: 134430720, PixelInfo: 852816
 Data: 134430720, PixelInfo: 1258536
 Data: 134430720, PixelInfo: 906659
 Data: 134430720, PixelInfo: 998548
 Data: 134430720, PixelInfo: 2072007
 Data: 134430720, PixelInfo: 2889998  // <--- CRASH
Nerrolken
  • 1,975
  • 3
  • 24
  • 53

0 Answers0