How to check if UIImage has transparency

Viewed 849

I use this function to detect if UIImage has transparency:

extension UIImage {
  public func isTransparent() -> Bool {
    guard let alpha: CGImageAlphaInfo = self.cgImage?.alphaInfo else { return false }
    return alpha == .first || alpha == .last || alpha == .premultipliedFirst || alpha == .premultipliedLast
  }
}

But it doesn't work. I tried it with a png Image with no transparency but it still return true.

Loop for each pixel is not a good idea because it's too expensive i guess. Any idea how to check if UIImage has transparency, like this image: image

2 Answers

You asked about Swift. Menaim gave a useful answer, but in Objective-C.

Here is a Swift version:

extension UIImage {
    var hasAlpha: Bool {
        guard let alphaInfo = self.cgImage?.alphaInfo else {return false}
        return alphaInfo != CGImageAlphaInfo.none &&
            alphaInfo != CGImageAlphaInfo.noneSkipFirst &&
            alphaInfo != CGImageAlphaInfo.noneSkipLast
    }
}

I just tested the above on a PNG image with no alpha channel and it worked.

Here is a PNG image with no alpha channel (Assuming SO's site preserves it...) PNG image with no alpha

Your solution seems to be good and working without issues but you can check out this one as well:

- (BOOL)hasAlpha : (UIImage*) img
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(img.CGImage);
    return (
            alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast
            );

}
Related