【发布时间】:2015-05-05 05:13:39
【问题描述】:
我已经对此进行了详尽的搜索,并且我知道之前已经发布过关于 NSBitmapImageRep 的类似问题,但它们似乎都不是针对我正在尝试做的事情,这很简单:
- 从桌面读取图像(但不显示)
- 创建该图像的 NSBitmap 表示
- 遍历像素以更改某些颜色
- 将修改后的位图表示另存为单独的文件
因为我从来没有使用过位图,所以我想我会先尝试创建并保存一个,然后再担心以后修改像素。这看起来很简单,但我只是无法让它工作。除了文件保存方面,大部分代码都是从 StackOverflow 上的另一个答案中借用的,如下所示:
-(void)processBitmapImage:(NSString*)aFilepath
{
NSImage *theImage = [[NSImage alloc] initWithContentsOfFile:aFilepath];
if (theImage)
{
CGImageRef CGImage = [theImage CGImageForProposedRect:nil context:nil hints:nil];
NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:CGImage];
NSInteger width = [imageRep pixelsWide];
NSInteger height = [imageRep pixelsHigh];
long rowBytes = [imageRep bytesPerRow];
// above matches the original size indicating NSBitmapImageRep was created successfully
printf("WIDE pix = %ld\n", width);
printf("HIGH pix = %ld\n", height);
printf("Row bytes = %ld\n", rowBytes);
// We'll worry about this part later...
/*
unsigned char* pixels = [imageRep bitmapData];
int row, col;
for (row=0; row < height; row++)
{
// etc ...
for (col=0; col < width; col++)
{
// etc...
}
}
*/
// So, let's see if we can just SAVE the (unmodified) bitmap first ...
NSData *pngData = [imageRep representationUsingType: NSPNGFileType properties: nil];
NSString *destinationStr = [self pathForDataFile];
BOOL returnVal = [pngData writeToFile:destinationStr atomically: NO];
NSLog(@"did we succeed?:%@", (returnVal ? @"YES": @"NO")); // the writeToFile call FAILS!
[imageRep release];
}
[theImage release];
}
虽然我喜欢这段代码的简单性,但未来的另一个潜在问题可能是 Apple 文档建议我们将使用“initWithCGImage”返回的位图视为只读对象……
谁能告诉我这段代码哪里出了问题,以及如何修改它才能工作。虽然整体概念在我的非专家眼中看起来不错,但我怀疑我犯了一个愚蠢的错误并忽略了一些非常基本的东西。在此先感谢:-)
【问题讨论】:
标签: objective-c macos nsimage