CodingIsComplex
CodingIsComplex

Reputation: 331

Converting CGImageRef to NSData

I have a CGImageRef that I want to convert to NSData without saving it into some file. Right now, I am doing this by saving the image to some temporary location and then retrieving this to a NSData. How can I do this without saving the image?

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]];

Upvotes: 4

Views: 5458

Answers (2)

arturdev
arturdev

Reputation: 11039

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: @{}];

Upvotes: 7

CodingIsComplex
CodingIsComplex

Reputation: 331

I was able to do this in the following manner:

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;

Upvotes: 9

Related Questions