31

If I instantiate a UIImage like this :

UIImage *image = [[UIImage alloc] init];

The object is created but it doesn't contain any image.

How I can check if my object contains an image or not?

Jonathan
  • 873
  • 3
  • 9
  • 23

4 Answers4

69

You can check if it has any image data.

UIImage* image = [[UIImage alloc] init];

CGImageRef cgref = [image CGImage];
CIImage *cim = [image CIImage];

if (cim == nil && cgref == NULL)
{
    NSLog(@"no underlying data");
}
[image release];

Swift Version

let image = UIImage()

let cgref = image.cgImage
let cim = image.ciImage

if cim == nil && cgref == nil {
    print("no underlying data")
}
Jalil
  • 1,167
  • 11
  • 34
Kreiri
  • 7,840
  • 5
  • 30
  • 36
16

Check for cgImage or ciImage, in Swift 3

public extension UIImage {

  public var hasContent: Bool {
    return cgImage != nil || ciImage != nil
  }
}

CGImage: If the UIImage object was initialized using a CIImage object, the value of the property is NULL.

CIImage: If the UIImage object was initialized using a CGImageRef, the value of the property is nil.

onmyway133
  • 45,645
  • 31
  • 257
  • 263
  • Crashes if there is no image... Unexpectedly found nil while unwrapping an Optional – dub Aug 20 '20 at 22:04
0

Check with CGImageRef with itself wheather it contains null value means UIImage object not contains image.......

0

This is updated version of @Kreiri, I put in a method and fixed logic error:

- (BOOL)containsImage:(UIImage*)image {
    BOOL result = NO;

    CGImageRef cgref = [image CGImage];
    CIImage *cim = [image CIImage];

    if (cim != nil || cgref != NULL) { // contains image
        result = YES;
    }

    return result;
}

An UIImage could only based on CGImageRef or CIImage. If both is nil means there is no image. Example use of giving method:

if (![self containsImage:imageview.image]) {
    [self setImageWithYourMethod];
}

hope it will help someone.

MGY
  • 7,245
  • 5
  • 41
  • 74