objective-c - 将 NSImage 保存为 NSData 时出错

标签 objective-c cocoa nsdata nsimage

我使用以下代码将电影的帧保存到桌面:

NSCIImageRep *imageRep = [NSCIImageRep imageRepWithCIImage:[CIImage imageWithCVImageBuffer:imageBuffer]];
NSImage *image = [[[NSImage alloc] initWithSize:[imageRep size]] autorelease];
[image addRepresentation:imageRep];
CVBufferRelease(imageBuffer);

NSArray *representations = [image representations];
NSData *bitmapData = [NSBitmapImageRep representationOfImageRepsInArray:representations usingType:NSJPEGFileType properties:nil];
[bitmapData writeToFile:@"/Users/ricky/Desktop/MyImage.jpeg" atomically:YES];

在代码的倒数第二行,我在控制台中收到以下消息,但没有结果保存到桌面:

<Error>: CGImageDestinationFinalize image destination does not have enough images
CGImageDestinationFinalize failed for output type 'public.jpeg'

NSImage 仍然是整个方法调用的分配对象,因此我不确定为什么会收到有关图像数量不足的投诉。

如果有任何帮助,我将不胜感激。 提前致谢, 瑞奇。

最佳答案

我认为问题的根源在于您将一个 NSCIImageRep 对象数组传递给representationOfImageRepsInArray:usingType:properties:,我相信它需要一个 NSBitmapImageRep 对象数组。

您想要做的是从 CIImage 创建一个 NSBitmapImageRep。然后您可以使用它写入磁盘。大致是:

CIImage *myImage = [CIImage imageWithCVImageBuffer:imageBuffer]; 
NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCIImage:myImage];
NSData *jpegData [bitmapRep representationUsingType:NSJPEGFileType properties:nil];
[jpegData writeToFile:@"/Users/ricky/Desktop/MyImage.jpeg" atomically:YES];

当然,您希望处理任何错误情况,并可能传递一个属性字典来微调 JPEG 创建。

关于objective-c - 将 NSImage 保存为 NSData 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2340710/

相关文章:

objective-c - 未分配对象指针被释放的 iOS Objective-C 错误

objective-c - obj-c/cocoa : When I click a button, 无限循环开始,数据似乎已损坏?

objective-c - 如何在 Objective-C 中声明类级别的属性?

objective-c - 如何将NULL字符(\000)编码为NSData?

ios - 强制按钮看起来被按下?

ios - iOS Google Now 如何显示不同的卡片模板

ios - PushViewController 导致黑屏,没有 Storyboard

iphone - 在 Objective-C 中是否有一个好的/最好的方法来扩展嵌套类?

ios - 将 NSData 转换为 SecKeyRef

ios - 如何从 NSData 对象获取 JSON 对象数组