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];
Run Code Online (Sandbox Code Playgroud)
使用显示的代码,我得到一个运行时错误: - [NSImageRep imageRepWithContentsOfFile:]:无法识别的选择器发送到实例0x100147070.
我试过用以下代码替换第二行代码:
NSImage *controlImage = [[NSImage alloc] initWithContentsOfFile:filePath];
NSBitmapImageRep *controlBitmap = [[NSBitmapImageRep alloc] initWithData:controlImage];
Run Code Online (Sandbox Code Playgroud)
但这会产生编译器错误"不兼容类型",说initWithData想要NSData变量而不是NSImage.
我还尝试了各种其他方法来完成这项工作,但由于编译器或运行时错误,所有方法都不成功.有人可以帮我弄这个吗?我最终需要以相同的方式加载一些PNG文件(因此,对两者都有一致的技术会很好).
如果你知道一个更简单/更简单的方法来完成我想要做的事情(即,将图像变成二维数组),而不是使用NSBitmapImageRep,那么请告诉我!顺便说一句,我知道路径是有效的(用fileExistsAtPath确认) - outLabel中的文件名是一个.jpg扩展名的文件.
谢谢你的帮助!
简单!
NSImage *controlImage = [[NSImage alloc] initWithContentsOfFile:filePath];
NSBitmapImageRep *imageRep = [[controlImage representations] objectAtIndex:0];
Run Code Online (Sandbox Code Playgroud)
然后得到实际的位图像素数据:
unsigned char *pixelData = [imageRep bitmapData];
Run Code Online (Sandbox Code Playgroud)
如果您的图像有多个表示(可能没有),您可以将它们从同一个数组中取出.相同的代码适用于.png图像.