【问题标题】:Getting bitmap data from JPEG image using Cocoa使用 Cocoa 从 JPEG 图像中获取位图数据
【发布时间】:2011-12-20 13:11:06
【问题描述】:

我需要从 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 等。

什么是最简单的方法,如果有代码sn-p,那就太好了。

谢谢!

【问题讨论】:

    标签: cocoa image


    【解决方案1】:

    你在正确的轨道上。正如您所注意到的,有很多方法可以做到这一点。

    一旦你有了一个 NSImage,你就可以创建一个位图表示,并直接访问它的字节。获取 NSBitmapImageRep 的一种简单方法是这样做:

    NSBitmapImageRep* imageRep = [[[NSBitmapImageRep alloc] initWithData:[tempImage TIFFRepresentation]] autorelease];
    
    unsigned char* bytes = [imageRep bitmapData];
    int bitsPerPixel  = [imageRep bitsPerPixel];
    // etc
    

    执行 TIFFRepresentation 步骤比直接访问 NSImage 的表示更安全。

    【讨论】:

    • 感谢您的帮助,但由于某种原因,图像未加载,或者 BitmapImageRep 无法正常工作,因为 bitsPerPixel 的值为 0。如何查看图像是否已加载(抱歉,我的 Cocoa 腿很新)。我在原始帖子中编辑了代码以反映更改
    • 我想出了如何验证它,但似乎仍然无法加载图像。该文件存在于该文件夹中。
    • 如果您在调试器中单步调试代码,您应该能够看到失败的原因。如果它不加载图像,则 tempImage 将为 nil。等等。调试器是你的朋友。
    • 代替 NSString* imageName=[[NSBundle mainBundle] pathForResource:@"/Users/me/Temp/oxberry.jpg" ofType:@"JPG"];你应该做 NSString* imageName=[[NSBundle mainBundle] pathForResource:@"oxberry" ofType:@"jpg"];其中 oxberry.jpg 是您在项目中包含的文件。如果您只想包含磁盘上特定位置的文件,则根本不需要 pathForResource 的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    相关资源
    最近更新 更多