Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]];
like image 715
CodingIsComplex Avatar asked Dec 05 '22 17:12

CodingIsComplex


1 Answers

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;
like image 52
CodingIsComplex Avatar answered Dec 21 '22 19:12

CodingIsComplex