4

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]];
CodingIsComplex
  • 291
  • 1
  • 3
  • 12
  • 2
    You may found some info there: http://stackoverflow.com/questions/19527902/converting-nsdata-to-cgimage-and-then-back-to-nsdata-makes-the-file-too-big – Larme Jun 15 '16 at 11:59
  • This answer uses the same concept that I am currently using. But involves writing to disk and then reading, I want to change it. So please suggest something else – CodingIsComplex Jun 15 '16 at 12:12

2 Answers2

9

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;
CodingIsComplex
  • 291
  • 1
  • 3
  • 12
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: @{}];
arturdev
  • 10,884
  • 2
  • 39
  • 67