2012-07-08 42 views
1

我想根據某些變量修改NSImage像素的顏色,而不使用過多的工具包相關庫(例如:CIImage)。所以,以後我可以專注於像素操作算法,並保持它們與平臺無關。在可可中操作NSImage的像素

我的方法是子類NSImage中,並添加屬性

NSBitmapImageRep *originalImage; 

在開始階段,我做的:

-(id) initWithContentsOfFile:(NSString *)fileName 
{ 
    if([super initWithContentsOfFile:fileName]){ 
     NSRect rect = NSMakeRect(0.0, 0.0, self.size.width, self.size.height); 
     [self lockFocus]; 
     originalImage = [[NSBitmapImageRep alloc] initWithFocusedViewRect:rect]; 
     [self unlockFocus]; 
    } 
    return self; 
} 

現在,當我嘗試更新我做的圖像:

-(void) updateWithVariables:... 
{ 
    NSInteger width = [originalImage pixelsWide]; 
    NSInteger height = [originalImage pixelsHigh]; 
    NSInteger count = width * height * 4; 

    unsigned char *bytes = (unsigned char *)calloc(count, sizeof(unsigned char)); 

    // bytes manipulation 

    NSBitmapImageRep* newImg = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:&bytes 
                     pixelsWide:width 
                     pixelsHigh:height 
                    bitsPerSample:[originalImage bitsPerSample] 
                    samplesPerPixel:[originalImage samplesPerPixel] 
                     hasAlpha:TRUE 
                     isPlanar:[originalImage isPlanar] 
                    colorSpaceName:[originalImage colorSpaceName] 
                    bitmapFormat:[originalImage bitmapFormat] 
                     bytesPerRow:[originalImage bytesPerRow] 
                    bitsPerPixel:[originalImage bitsPerPixel]]; 
    while([[self representations] count] > 0){ 
     NSBitmapImageRep *rep = [[self representations] objectAtIndex: 0]; 
     [self removeRepresentation:rep]; 
    } 

    [self addRepresentation:newImg]; 
    [newImg release]; 
} 

但圖像不變。我不確定是否必須使用表示或將包含NSImageView更改爲上下文以繪製新圖像。

謝謝!

回答

1

this page蘋果說:

款待NSImage中和它的圖像表示爲不可變對象。 NSImage的目標是提供一種在目標畫布上顯示圖像的有效方法。避免直接操作圖像表示的數據,特別是如果有其他操作數據的選擇,例如將圖像和其他內容合成爲新的圖像對象。

所以,你應該創建一個新的圖像,當你想像素改變。