iPhone CGContextRef CGBitmapContextCreate unsupported parameter combination

前端 未结 5 809
抹茶落季
抹茶落季 2020-12-06 11:45

In my application I need to resize and crop some images, stored locally and online. I am using Trevor Harmon\'s tutorial which implements UIImage+Resize.

<
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 12:31

    Replying here since I had the exact same pixel format when I got this error. I hope this answer helps someone.

    The reason it was failing, in my case, was that kCGImageAlphaLast isn't a permitted value anymore on iOS 8, although it works well on iOS 7. The 32 pbb, 8 bpc combination only allows kCGImageAlphaNoneSkip* and kCGImageAlphaPremultiplied* for the Alpha Info. Apparently this was a problem always, but wasn't enforced before iOS 8. Here's my solution:

    - (CGBitmapInfo)normalizeBitmapInfo:(CGBitmapInfo)oldBitmapInfo {
        //extract the alpha info by resetting everything else
        CGImageAlphaInfo alphaInfo = oldBitmapInfo & kCGBitmapAlphaInfoMask;
    
        //Since iOS8 it's not allowed anymore to create contexts with unmultiplied Alpha info
        if (alphaInfo == kCGImageAlphaLast) {
            alphaInfo = kCGImageAlphaPremultipliedLast;
        }
        if (alphaInfo == kCGImageAlphaFirst) {
            alphaInfo = kCGImageAlphaPremultipliedFirst;
        }
    
        //reset the bits
        CGBitmapInfo newBitmapInfo = oldBitmapInfo & ~kCGBitmapAlphaInfoMask;
    
        //set the bits to the new alphaInfo
        newBitmapInfo |= alphaInfo;
    
        return newBitmapInfo;
    }
    

    In my case the failing piece of code looked like this, where imageRef is a CGImageRef of a PNG loaded from the app bundle:

    CGContextRef bitmap = CGBitmapContextCreate(NULL,
                                                    newRect.size.width,
                                                    newRect.size.height,
                                                    CGImageGetBitsPerComponent(imageRef),
                                                    0,
                                                    CGImageGetColorSpace(imageRef),
                                                    CGImageGetBitmapInfo(imageRef));
    

    Sources: https://stackoverflow.com/a/19345325/3099609

    https://developer.apple.com/library/mac/DOCUMENTATION/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html#//apple_ref/doc/uid/TP30001066-CH203-BCIBHHBB

提交回复
热议问题