1

我正在尝试从一个对象中获取数据NSImage并将其作为 RGBA(每通道 8 位)的 32 位 BMP 数据写出NSData。这是我的代码:

- (NSData *)dataRepresentation {
    NSImage *textureImage = self.textureImage;
    NSSize size = [textureImage size];
    NSImageRep *imageRep = [[textureImage representations] objectAtIndex:0];
    NSRect rect = NSMakeRect(0, 0, size.width, size.height);

    CGImageRef outputImage = [imageRep CGImageForProposedRect:&rect context:NULL hints:nil];
    CFMutableDataRef textureData = CFDataCreateMutable(kCFAllocatorDefault, size.width*size.height*4+54);
    CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData(textureData, kUTTypeBMP, 1, NULL);

    CFStringRef keys[1] = {kCGImagePropertyHasAlpha};
    CFBooleanRef values[1] = {kCFBooleanTrue};
    CFDictionaryRef options = CFDictionaryCreate(kCFAllocatorDefault, (const void **)keys, (const void **)values, 1, NULL, NULL);

    CGImageDestinationAddImage(imageDestination, outputImage, options);
    CFRelease(options);
    CGImageDestinationFinalize(imageDestination);
    CFRelease(imageDestination);
    return (NSData *)CFBridgingRelease(textureData);
}

结果数据缺少 Alpha 通道。它正确地每个组件有 8 位,但完全缺少 alpha 通道。我认为带有kCGImagePropertyHasAlpha属性的选项字典可以解决它,但它没有。无论如何,我不确定这是否真的是正确的方法,有人可以在这里指出我正确的方向吗?

4

0 回答 0