Permalink
Browse files

Merge pull request #299 from Reflejo/master

Fix "Alpha on JPEG with no alpha" when decoding
  • Loading branch information...
rs committed Feb 16, 2013
2 parents b27d571 + de19c24 commit 5f535602f1496bd68197e2bd851e0857f1117f4c
Showing with 35 additions and 2 deletions.
  1. +35 −2 SDWebImage/SDWebImageDecoder.m
@@ -18,8 +18,41 @@ + (UIImage *)decodedImageWithImage:(UIImage *)image
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);
+
+ int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask);
+ BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone ||
+ infoMask == kCGImageAlphaNoneSkipFirst ||
+ infoMask == kCGImageAlphaNoneSkipLast);
+
+ // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB.
+ // https://developer.apple.com/library/mac/#qa/qa1037/_index.html
+ if (infoMask == 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 (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3)
+ {
+ // Unset the old alpha info.
+ bitmapInfo &= ~kCGBitmapAlphaInfoMask;
+ 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;

0 comments on commit 5f53560

Please sign in to comment.