我想根据一些变量修改 NSImage 像素的颜色,而不使用太多依赖于工具包的库(例如:CIImage)。这样以后我就可以专注于像素操作算法并保持它们独立于平台。
我的方法是继承 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 更改为上下文来绘制新图像。
谢谢!