如何在目标c中获得图像的像素值(rgba)?

时间:2018-08-14 06:18:05

标签: objective-c

我指的是下面的链接,但在

处出错
unsigned char* pixels = [image rgbaPixels];

  

“ UIImage”没有可见的@interface声明选择器“ rgbaPixels”

所以,我的问题是如何获取物镜c中图像的像素值(rgba)

链接参考

https://www.transpire.com/insights/blog/obtaining-luminosity-from-an-ios-camera

1 个答案:

答案 0 :(得分:1)

您遇到了错误

  

“ UIImage”没有可见的@interface声明选择器“ rgbaPixels”

由于rgbaPixels是自定义函数,因此博客由他自己编写。

您可以自己创建一个

首先,创建UIImage

类别

.h文件

@interface UIImage (ColorData)
- (unsigned char *)rgbaPixels;
@end

.m文件

#import "UIImage+ColorData.h"

@implementation UIImage (ColorData)

- (unsigned char *)rgbaPixels {
    // First get the image into your data buffer
    CGImageRef imageRef = [self CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
    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);
    return rawData;
}

@end