简体   繁体   中英

How to get CGImageRef from CGContextRef?

I am trying to add two images into context, however it does not work and throws

GBitmapContextCreateImage: invalid context 0x0

error. I use the following code:

//some image
CGImageRef image = ...
//some image as well, but masked. Works perfectly.
CGImageRef blurredAndMasked = CGImageCreateWithMask(blurred, mask);
//Both images are fine. Sure.

//Initializing the context and color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(nil, frameSize.width, frameSize.height, 8, 0, colorSpace, kCGBitmapAlphaInfoMask);

//Drawing images into the context
CGContextDrawImage(ctx, CGRectMake(0, 0, frameSize.width, frameSize.height), image);
CGContextDrawImage(ctx, CGRectMake(0, 0, frameSize.width, frameSize.height), blurredAndMasked);

//getting the resulting image
CGImageRef ret = CGBitmapContextCreateImage(ctx);

//releasing the stuff
CGImageRelease(image);
CGImageRelease(blurred);
CGImageRelease(blurredAndMasked);
CGColorSpaceRelease(colorSpace);
CGContextRelease(ctx);

this seems fine but the resulting images are all black or look very similar to this: 形象不佳

What should be changed in the code? Thanks in advance!

kCGBitmapAlphaInfoMask is not a valid value for the last ( bitmapInfo ) argument to CGBitmapContextCreate . It is a mask (hence the name) you can use with the & operator to get just the CGImageAlphaInfo out of a CGBitmapInfo value. You would never pass kCGBitmapAlphaInfoMask where a CGBitmapInfo or CGImageAlphaInfo is expected.

Assuming you don't need a specific byte order, I believe this is the highest performance pixel format with alpha channel on iOS:

CGContextRef ctx = CGBitmapContextCreate(nil,
    frameSize.width, frameSize.height, 8, 0, colorSpace,
    kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);

And this should be the highest performance without alpha channel:

CGContextRef ctx = CGBitmapContextCreate(nil,
    frameSize.width, frameSize.height, 8, 0, colorSpace,
    kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst);

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