Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSData to CGDataProviderRef on iphone sdk?

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

like image 907
GAS Avatar asked Aug 21 '10 01:08

GAS


2 Answers

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);
like image 138
Todd Yandell Avatar answered Nov 06 '22 07:11

Todd Yandell


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.

like image 3
Stefan Arentz Avatar answered Nov 06 '22 06:11

Stefan Arentz