我需要从 JPEG 或 PNG 文件中提取原始 RGB 位图数据,其中包含文件中的所有位,而不是窗口或颜色转换版本。
我是 Cocoa 新手,但看起来我使用 NSImage 打开图像,如下所示:
NSString* imageName=[[NSBundle mainBundle] pathForResource:@"/Users/me/Temp/oxberry.jpg" ofType:@"JPG"];
NSImage* tempImage=[[NSImage alloc] initWithContentsOfFile:imageName];
NSBitmapImageRep* imageRep=[[[NSBitmapImageRep alloc] initWithData:[tempImage TIFFRepresentation]] autorelease];
unsigned char* bytes=[imageRep bitmapData];
int bits=[imageRep bitsPerPixel];
然后,要获取位图数据,似乎有很多选择:Bitmapimage、CGImage 等。
最简单的方法是什么,如果有代码片段,那就太好了。
谢谢!
最佳答案
你走在正确的道路上。正如您所注意到的,有很多方法可以做到这一点。
一旦你有了一个 NSImage,你就可以创建一个位图表示,并直接访问它的字节。获取 NSBitmapImageRep 的一个简单方法是执行以下操作:
NSBitmapImageRep* imageRep = [[[NSBitmapImageRep alloc] initWithData:[tempImage TIFFRepresentation]] autorelease];
unsigned char* bytes = [imageRep bitmapData];
int bitsPerPixel = [imageRep bitsPerPixel];
// etc
执行 TIFFRepresentation 步骤比直接访问 NSImage 的表示更安全。
关于cocoa - 使用 Cocoa 从 JPEG 图像获取位图数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8575982/