Objective-C/ cocoa : 我需要将图像从 JPG 文件加载到二维数组中,以便我可以访问每个像素。我正在尝试(未成功)将图像加载到 NSBitmapImageRep 中。我尝试了以下两行代码的几种变体:
NSString *filePath = [NSString stringWithFormat: @"%@%@",@"/Users/adam/Documents/phoneimages/", [outLabel stringValue]]; //this coming from a window control
NSImageRep *controlBitmap = [[NSImageRep alloc] imageRepWithContentsOfFile:filePath];
根据显示的代码,我收到运行时错误:-[NSImageRep imageRepWithContentsOfFile:]: 无法识别的选择器发送到实例 0x100147070。
我尝试将第二行代码替换为:
NSImage *controlImage = [[NSImage alloc] initWithContentsOfFile:filePath];
NSBitmapImageRep *controlBitmap = [[NSBitmapImageRep alloc] initWithData:controlImage];
但这会产生编译器错误“不兼容类型”,指出 initWithData 需要 NSData 变量而不是 NSImage。
我也尝试过各种其他方法来完成此操作,但由于编译器或运行时错误,所有方法均未成功。有人可以帮我弄这个吗?我最终将需要以相同的方式加载一些 PNG 文件(因此最好为两者采用一致的技术)。
而且,如果您知道一种更简单/更简单的方法来完成我正在尝试做的事情(即,将图像放入二维数组),而不是使用 NSBitmapImageRep,请告诉我!顺便说一下,我知道该路径是有效的(通过 fileExistsAtPath 确认)——并且 outLabel 中的文件名是一个扩展名为 .jpg 的文件。
感谢您的帮助!
最佳答案
简单!
NSImage *controlImage = [[NSImage alloc] initWithContentsOfFile:filePath];
NSBitmapImageRep *imageRep = [[controlImage representations] objectAtIndex:0];
然后获取实际的位图像素数据:
unsigned char *pixelData = [imageRep bitmapData];
如果您的图像有多个表示(可能没有),您可以从同一个数组中取出它们。相同的代码将适用于您的 .png 图像。
关于objective-c - 如何将 JPG 文件加载到 NSBitmapImageRep?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2954786/