如何将JPG文件加载到NSBitmapImageRep中? [英] How to load JPG file into NSBitmapImageRep?

查看:64
本文介绍了如何将JPG文件加载到NSBitmapImageRep中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C/可可粉:我需要将图像从JPG文件加载到二维数组中,以便可以访问每个像素.我正在尝试(未成功)将图像加载到NSBitmapImageRep中.我在以下两行代码上尝试了几种变体:

Objective-C / Cocoa: I need to load the image from a JPG file into a two dimensional array so that I can access each pixel. I am trying (unsuccessfully) to load the image into a NSBitmapImageRep. I have tried several variations on the following two lines of code:

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.

With the code shown, I get a runtime error: -[NSImageRep imageRepWithContentsOfFile:]: unrecognized selector sent to instance 0x100147070.

我尝试将第二行代码替换为:

I have tried replacing the second line of code with:

NSImage *controlImage = [[NSImage alloc] initWithContentsOfFile:filePath];
NSBitmapImageRep *controlBitmap = [[NSBitmapImageRep alloc] initWithData:controlImage];

但是这会产生一个编译器错误不兼容类型",表示initWithData想要一个NSData变量而不是一个NSImage.

But this yields a compiler error 'incompatible type' saying that initWithData wants a NSData variable not an NSImage.

我还尝试了其他各种方法来完成此操作,但是由于编译器或运行时错误,所有方法均未成功.有人可以帮我弄这个吗?我最终将需要以相同的方式加载一些PNG文件(因此,对两者都采用一致的技术会很好.)

I have also tried various other ways to get this done, but all are unsuccessful either due to compiler or runtime error. Can someone help me with this? I will eventually need to load some PNG files in the same way (so it would be nice to have a consistent technique for both).

如果您知道一种更容易/更简单的方法来完成我想做的事情(即,将图像放入二维数组中),而不是使用NSBitmapImageRep,那么请告诉我!顺便说一句,我知道路径是有效的(已通过fileExistsAtPath确认)-outLabel中的文件名是带有.jpg扩展名的文件.

And if you know of an easier / simpler way to accomplish what I am trying to do (i.e., get the images into a two-dimensional array), rather than using NSBitmapImageRep, then please let me know! And by the way, I know the path is valid (confirmed with fileExistsAtPath) -- and the filename in outLabel is a file with .jpg extension.

感谢您的帮助!

推荐答案

容易!

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

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

Then to get the actual bitmap pixel data:

unsigned char *pixelData = [imageRep bitmapData];

如果图像具有多种表示形式(可能没有),则可以将它们从同一阵列中取出.相同的代码将适用于您的.png图像.

If your image has multiple representations (it probably doesn't), you can get them out of that same array. The same code will work for your .png images.

这篇关于如何将JPG文件加载到NSBitmapImageRep中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆