将CGImageRef转换为NSData

Cod*_*lex 3 cocoa objective-c

我有一个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]];
Run Code Online (Sandbox Code Playgroud)

art*_*dev 7

iOS版:

NSData *data = UIImageJPEGRepresentation([[UIImage alloc] initWithCGImage:img], 1)
Run Code Online (Sandbox Code Playgroud)

苹果系统:

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


Cod*_*lex 6

我能够以下列方式做到这一点:

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;
Run Code Online (Sandbox Code Playgroud)