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
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With