如何将 JPG 文件加载到 NSBitmapImageRep 中?

2024-05-12

Objective-C / 可可: 我需要将 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 的文件。

谢谢你的帮助!


Easy!

NSImage *controlImage = [[NSImage alloc] initWithContentsOfFile:filePath];
NSBitmapImageRep *imageRep = [[controlImage representations] objectAtIndex:0];

然后获取实际的位图像素数据:

unsigned char *pixelData = [imageRep bitmapData];

如果您的图像有多种表示形式(可能没有),您可以从同一个数组中获取它们。相同的代码适用于您的 .png 图像。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 JPG 文件加载到 NSBitmapImageRep 中? 的相关文章

随机推荐