我有一个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]];
答案 0 :(得分: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: @{}];
答案 1 :(得分: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;