我已经对此进行了详尽的搜索,并且我知道在NSBitmapImageRep之前已经发布了类似的问题,但是它们似乎都没有特定于我正在尝试做的事情,这很简单:
因为我之前从未尝试使用位图,我以为我只是尝试先创建并保存一个位图,并担心以后修改像素。这看起来非常简单,但我只是无法让它发挥作用。除了文件保存方面,大多数代码都是从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 docs建议我们将用'initWithCGImage'作为只读对象返回的位图处理......
任何人都可以告诉我这个代码出错的地方,以及我如何修改它来工作。虽然整体概念看起来对我的非专家眼睛来说是好的,但我怀疑我犯了一个愚蠢的错误并且忽略了一些非常基本的东西。在此先感谢: - )
答案 0 :(得分:0)
创建NSBitmapImageRep
这是一种相当迂回的方式。尝试创建它:
NSBitmapImageRep* imageRep = [NSBitmapImageRep imageRepWithContentsOfFile:aFilepath];
当然,上面没有给你图像代表对象的所有权,所以不要在最后发布它。