gpt4 book ai didi

cocoa - 在 Cocoa 中操作 NSImage 的像素

转载 作者:行者123 更新时间:2023-12-03 17:24:20 24 4
gpt4 key购买 nike

我想根据一些变量修改 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 更改为上下文来绘制新图像。

谢谢!

最佳答案

关于this page苹果说:

Treat NSImage and its image representations as immutable objects. The goal of NSImage is to provide an efficient way to display images on the target canvas. Avoid manipulating the data of an image representation directly, especially if there are alternatives to manipulating the data, such as compositing the image and some other content into a new image object.

因此,当您希望更改像素时,您可能应该创建一个新图像。

关于cocoa - 在 Cocoa 中操作 NSImage 的像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11383442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com