简体   繁体   中英

How can I get a CGImageRef from a file?

So I know you can get a CGImage from a file using UIImage...

UIImage *img = [UIImage imageNamed:@"name.bmp"];
[img CGImage];

But, is there a way to get a CGImageRef without using a UIImage ?

(I am trying this in a static library which doesn't have access to UIKit) I could use other frameworks if necessary, just not UIKit. Would CIImage work? Or NSBitmapImageRep ?

You can get it from NSData:

CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData((CFDataRef)[NSData dataWithContentsOfFile:@""]);
CGImageRef image = CGImageCreateWithPNGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault); // Or JPEGDataProvider

You would have to be certain that the data was a JPEG or a PNG for this to work.

You have to understand that using [UIImage imageNamed:@"name.bmp"] works through UIKit framework. This is not thread safe. Example for dispatch_apply you must use Quartz framework.

// Through Quartz
NSString *maskFilePath = [[NSBundle mainBundle] pathForResource:@"mask" ofType:@"png"];
CGDataProviderRef dataProvider = CGDataProviderCreateWithFilename([maskFilePath UTF8String]);
CGImageRef maskRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM