ObjectiveC - 获取CGImage的像素位置

时间:2016-06-16 15:57:53

标签: ios objective-c pixels

我试图循环通过CGImage的像素并获取每个像素的点位置。我已设法计算所有像素,但我无法弄清楚如何获得每个像素的点。

我怎么能实现这个目标?

+ (NSUInteger) getPixelsOfImage:(UIImage*)image {


    // 1. Get pixels of image
    CGImageRef inputCGImage = [image CGImage];
    NSUInteger width = CGImageGetWidth(inputCGImage);
    NSUInteger height = CGImageGetHeight(inputCGImage);

    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;

    UInt32 * pixels;
    pixels = (UInt32 *) calloc(height * width, sizeof(UInt32));

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixels, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast|kCGBitmapByteOrder32Big);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), inputCGImage);

    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);


    NSUInteger pixelsCount = 0;

    UInt32 * currentPixel = pixels;
    for (NSUInteger j = 0; j < height; j++) {
        for (NSUInteger i = 0; i < width; i++) {

                pixelsCount++;

            currentPixel++;
        }
    }

    free(pixels);

    return pixelsCount;
}

0 个答案:

没有答案