[英]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. 我在CGContextDrawImage调用中收到EXEC_BAD_ACCESS错误并尝试追溯它。 I have a PNG image and running a UIImagePNGRepresentation o it gives me NSData instance.
我有一个PNG图像并运行UIImagePNGRepresentation o它给了我NSData实例。
I need to convert this to CGImageRef instance, so I can run the CGImageCreateWithPNGDataProvider method with this CGImageRef. 我需要将其转换为CGImageRef实例,因此我可以使用此CGImageRef运行CGImageCreateWithPNGDataProvider方法。
I tried two ways: 1) To cast it. 我尝试了两种方法:1)投下它。
CGImageRef ref = (CGDataProvider)nsdata; CGImageRef ref =(CGDataProvider)nsdata;
2) To run CGDataProviderCreateWithCFData(nsdata); 2)运行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.
我尝试第二种情况的原因,即使我有NSData而不是CFData是因为我记得读它接受两者。 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? 有没有办法可以使用我的PNG NSData创建一个没有损坏的CGImage? Please help.
请帮忙。
THanks 谢谢
Your second try is almost right. 你的第二次尝试几乎是对的。 CFData and NSData are “toll-free bridged”.
CFData和NSData是“免费桥接”。 Anything that accepts a CFDataRef also accepts NSData (and vice-versa) — you just have to cast correctly.
任何接受CFDataRef的东西也接受NSData(反之亦然) - 你只需要正确投射。
You need: 你需要:
CGDataProviderCreateWithCFData((CFDataRef)myNSData);
The first is very wrong. 第一个是非常错误的。 You can not turn an
NSData
instance into a CGImageRef
simply by casting it. 您无法通过强制转换将
NSData
实例转换为CGImageRef
。
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 . 您必须将
NSData
实例CFDataRef
转换为CFDataRef
但这完全合法,因为Apple称之为免费桥接 。
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. 我更喜欢使用更高级别的
UIImage
方法来加载图像,然后使用image.CGImage
来实现更低级别的Core Graphics功能。 Don't forget to properly retain the UIImage
if you need to keep it around. 如果需要保留
UIImage
,请不要忘记正确保留UIImage
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.