如何找出图像中的“特定像素的颜色”?
答
这取决于图像:)
的类型非常如果你有字节的数据,你知道它是如何安排,例如PNG使用RGBA那么你已经有了一条腿。
自由使用像CGImageGetBitsPerComponent和CGImageGetColorSpace这样的所有CGImageFunctions将成为您的指南。
获得实际的字节数据,CGImageDestinationCreateWithData创建一个写入到一个核心基础可变数据对象(NSMutableData */CFMutableDataRef)
如果这一切都是乱码图像的目的地,开始与Quart2D Programming Guide。
答
这里是非常简单的类的sceleton与图像作为位图一起工作。 当创建具有
ImageBitmap * imageBitmap = [[ImageBitmap alloc] initWithImage:myImageView.image bitmapInfo:kCGImageAlphaNoneSkipLast];
这个对象可以在(X,Y) 作为
Byte * pixel = [imageBitmap pixelAtX:x Y:y];
RGB分量在0,1,2字节所以
Byte red = pixel[0]; etc.
访问任何像素
您可以读取或写入像素,例如设置从像素中移除绿色分量:
pixel[1] = 0;
如果使用kCGImageAlphaPremultipliedLast像素[3]是α-
//ImageBitmap.h
@interface ImageBitmap : NSObject {
int height, width;
void * contextData;
CGContextRef context;
CGBitmapInfo bitmapInfo;
}
@property(assign) int height;
@property(assign) int width;
@property(readonly) CGContextRef context;
@property(readonly) void * contextData;
-(id)initWithSize:(CGSize)size bitmapInfo:(CGBitmapInfo)bmInfo;
-(id)initWithImage:(UIImage *)image bitmapInfo:(CGBitmapInfo)bmInfo;
-(CGContextRef)createBitmapContextWithData:(void *)data;
- (UIImage *)imageFromContext;
-(Byte *)pixelAtX:(NSInteger)pixelX Y:(NSInteger)pixelY;
//ImageBitmap.m
#import "ImageBitmap.h"
@implementation ImageBitmap
@synthesize width, height;
@synthesize context, contextData;
-(id)initWithSize:(CGSize)size bitmapInfo:(CGBitmapInfo)bmInfo{
if (self = [super init]) {
height = size.height;
width = size.width;
contextData = malloc(width * height * 4);
bitmapInfo = bmInfo;
context = [self createBitmapContextWithData:contextData];
}
return self;
}
-(id)initWithImage:(UIImage *)image bitmapInfo:(CGBitmapInfo)bmInfo{
[self initWithSize:image.size bitmapInfo:bmInfo];
CGContextDrawImage(context, CGRectMake(0, 0, width, height),image.CGImage);
return self;
}
-(CGContextRef) createBitmapContextWithData:(void *)data{
CGContextRef ctx = NULL;
int bitmapBytesPerRow = (width * 4);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
if (data == NULL){
return NULL;
}
ctx = CGBitmapContextCreate (data,
width,
height,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
bitmapInfo); //kCGImageAlphaNoneSkipLast or kCGImageAlphaPremultipliedLast
CGColorSpaceRelease(colorSpace);
return ctx;
}
- (UIImage *)imageFromContext{
CGImageRef cgImage = CGBitmapContextCreateImage(context);
return [UIImage imageWithCGImage:cgImage];
}
-(Byte *)pixelAtX:(NSInteger)pixelX Y:(NSInteger)pixelY{
return (Byte *)contextData + (width * pixelY + pixelX)*4;
}
@end
见[这个问题](http://stackoverflow.com/questions/3142178/nsbitmapimagerep-for-iphone-or-direct-pixel-access - 用于-cgimage/3142338#3142338) – drawnonward 2010-07-03 17:21:46