将CGImageRef转换为NSData

4

我有一个CGImageRef,我想将它转换为NSData而不将其保存到文件中。目前,我是通过将图像保存到某个临时位置,然后检索此位置以获取NSData来完成这个过程的。如何在不保存图像的情况下完成此操作?

CGImageRef img = [[self system_Application] getScreenShot];
NSString *tempDirectory = NSTemporaryDirectory();
CFURLRef url = (CFURLRef)[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/abc.jpg",tempDirectory]];

CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
CGImageDestinationAddImage(destination, img, nil);
if(!CGImageDestinationFinalize(destination))
    NSLog(@"Failed to write Image");

NSData *mydata = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/abc.jpg",tempDirectory]];

2
你可以在这里找到一些信息:https://dev59.com/g3jZa4cB1Zd3GeqPcEYT - Larme
这个答案使用了我目前正在使用的相同概念。但是涉及到写入磁盘然后读取,我想要改变它。所以请建议其他的东西。 - CodingIsComplex
2个回答

9
我能用以下方法做到这一点:
CFMutableDataRef newImageData = CFDataCreateMutable(NULL, 0);
CGImageDestinationRef destination = CGImageDestinationCreateWithData(newImageData, kUTTypePNG, 1, NULL);
CGImageDestinationAddImage(destination, img, nil);
if(!CGImageDestinationFinalize(destination))
    NSLog(@"Failed to write Image");
NSData *newImage = ( NSData *)newImageData;

7

iOS:

NSData *data = UIImageJPEGRepresentation([[UIImage alloc] initWithCGImage:img], 1)

MacOS:

NSImage *image = [[NSImage alloc] initWithCGImage:img size:NSSizeFromCGSize(CGSizeMake(100, 100))];
NSBitmapImageRep *imgRep = (NSBitmapImageRep *)[[image representations] objectAtIndex: 0];
NSData *data = [imgRep representationUsingType: NSPNGFileType properties: @{}];

这个问题被标记了为Cocoa,UIImage仅在Cocoa Touch中可用。 - jrturton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接