开发者

howto get pixel data based on a CGPoint (x,y)?

开发者 https://www.devze.com 2023-02-06 17:45 出处:网络
any ideas?Getting the pixel data based on a c开发者_如何学Gooordinate point.I haven\'t tested it, but it should work. image is an UIImage. The for loops through the image and retrieves the RGBA values

any ideas? Getting the pixel data based on a c开发者_如何学Gooordinate point.


I haven't tested it, but it should work. image is an UIImage. The for loops through the image and retrieves the RGBA values for each pixel. You can just remove the loop and replace xx and yy with your coordinate to get a single pixel.

CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);

// this loops through all the pixels
for(int yy = 0; yy<height; yy++) {
    for(int xx = 0; xx<width; xx++) {
        int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;

        short r = rawData[byteIndex];
        short g = rawData[byteIndex + 1];
        short b = rawData[byteIndex + 2];
        short a = rawData[byteIndex + 3];
    }
}

free(rawData);
0

精彩评论

暂无评论...
验证码 换一张
取 消