views:

191

answers:

3

I am getting EXEC_BAD_ACCESS errors in a CGContextDrawImage call and trying to trace it back. I have a PNG image and running a UIImagePNGRepresentation o it gives me NSData instance.

I need to convert this to CGImageRef instance, so I can run the CGImageCreateWithPNGDataProvider method with this CGImageRef.

I tried two ways: 1) To cast it.

CGImageRef ref = (CGDataProvider)nsdata;

2) To run CGDataProviderCreateWithCFData(nsdata);

First case returns empty image, though command doesnt fail. The reason I tried the second case, even though I have NSData and not CFData is because I remember reading it accepts both. Whatever be the reason, it is failing due to this.

Is there a way I can use my PNG NSData to create a CGImage that is not corrupted? Please help.

THanks

+1  A: 

The first is very wrong. You can not turn an NSData instance into a CGImageRef simply by casting it.

The second should work fine. You will have to cast the NSData instance to a CFDataRef but that is perfectly legal due to what Apple calls toll-free bridging.

Here is another and much easier method:

NSData* data = ... get raw image data from somewhere (PNG, JPEG, etc.) ...;
UIImage* image = [UIImage imageWithData: data];
CGImageRef imageRef = image.CGImage;

I prefer to use the higher level UIImage methods to load images and then use image.CGImage for lower level Core Graphics functions. Don't forget to properly retain the UIImage if you need to keep it around.

St3fan
`image.CGImage` is definitely better than `(CGImageRef)[(id)CGImageCreateWithPNGDataProvider((CGDataProviderRef)[(id)CGDataProviderCreateWithNSData((CFDataRef)UIImagePNGRepresentation(image)) autorelease],0,0,0) autorelease]`
tc.
A: 

Your second try is almost right. CFData and NSData are “toll-free bridged”. Anything that accepts a CFDataRef also accepts NSData (and vice-versa) — you just have to cast correctly.

You need:

CGDataProviderCreateWithCFData((CFDataRef)myNSData);
Todd Yandell
A: 

Thanks for all your suggestions. I tried both the CFDataRef cast for NSData and also the high level UIImage.CGImage that St3fan mentioned.

Anyways, I still get the EXC_BAD_ACCESS. I did verify that the CGDataProvider values are good, by writing back the data from the UIImage into a new image. It displayed fine. The exception is at the point where I try to do a CGContextDrawImage using this generated image.

CGContextRef mvcc = CGBitmapContextCreate (NULL, 120, 120, 8, 480, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipLast);
CGImageRef newSrc = myImageCreatedFromTheNSDataRepresentation.CGImage;
CGContextDrawImage(mvcc, CGRectMake(0, 0, 120, 120), newSrc); //EXC_BAD_ACCESS HERE

Is the BitMap Context I am creating wrong in any way? I have a null check for mvcc and it comes out as non-null. Thanks again.

GAS