2010-07-03 114 views

回答

1

這取決於圖像:)

的類型非常如果你有字節的數據,你知道它是如何安排,例如PNG使用RGBA那麼你已經有了一條腿。

自由使用像CGImageGetBitsPerComponent和CGImageGetColorSpace這樣的所有CGImageFunctions將成爲您的指南。

獲得實際的字節數據,CGImageDestinationCreateWithData創建一個寫入到一個核心基礎可變數據對象(NSMutableData */CFMutableDataRef)

如果這一切都是亂碼圖像的目的地,開始與Quart2D Programming Guide

0

這裏是非常簡單的類的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 
相關問題