From 12196f4de69268dc994ba3d5bc04a11568177520 Mon Sep 17 00:00:00 2001 From: Martin Conte Mac Donell Date: Thu, 17 Jan 2013 01:16:41 -0300 Subject: [PATCH] Fixed CGBitmapContextCreate warnings for invalid alpha properties --- SDWebImage/SDWebImageDecoder.m | 37 +++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/SDWebImage/SDWebImageDecoder.m b/SDWebImage/SDWebImageDecoder.m index 1b219c99..3efe661a 100644 --- a/SDWebImage/SDWebImageDecoder.m +++ b/SDWebImage/SDWebImageDecoder.m @@ -13,13 +13,44 @@ @implementation UIImage (ForceDecode) + (UIImage *)decodedImageWithImage:(UIImage *)image -{ +{ CGImageRef imageRef = image.CGImage; CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; - CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef); - CGContextRef context = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpace, CGImageGetBitmapInfo(imageRef)); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. + // https://developer.apple.com/library/mac/#qa/qa1037/_index.html + if ((bitmapInfo & kCGBitmapAlphaInfoMask) == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) + { + // Unset the old alpha info. + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + + // Set noneSkipFirst. + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } + // Some PNGs tell us they have alpha but only 3 components. Odd. + else if (((bitmapInfo & kCGBitmapAlphaInfoMask) & (kCGImageAlphaFirst | kCGImageAlphaLast)) != 0 + && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) + { + // Unset the old alpha info. + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + + // Set noneSkipFirst. + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } + + // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. + CGContextRef context = CGBitmapContextCreate(NULL, + imageSize.width, + imageSize.height, + CGImageGetBitsPerComponent(imageRef), + 0, + colorSpace, + bitmapInfo); + CGColorSpaceRelease(colorSpace); // If failed, return undecompressed image if (!context) return image;