7

I need to check if a file loaded into an UIImage object file is equal to another image and execute some actions if so. Unfortunately, it's not working.

emptyImage = UIImage(named: imageName)

if(image1.image != emptyImage) {
    // do something
} else {
    // do something
}

The above code always enters the if branch.

Cristik
  • 30,989
  • 25
  • 91
  • 127
Murat Kaya
  • 1,281
  • 3
  • 28
  • 52

3 Answers3

19

You can implement the equality operator on UIImage, which will ease your logic when it comes to comparing images:

func ==(lhs: UIImage, rhs: UIImage) -> Bool {
    lhs === rhs || lhs.pngData() == rhs.pngData()
}

The operator compares the PNG representation, with a shortcut if the arguments point to the same UIImage instance

This also enables the != operator on UIImage.

Note that the .pngData call and the byte-to-byte comparison might be a time consuming operation, so care to be taken when trying to compare large images.

Cristik
  • 30,989
  • 25
  • 91
  • 127
14

You cannot compare two UIImage objects using the != or == operators, one option is comparing as NSData using the UIImagePNGRepresentation to convert it to NSData objects, like in the following code:

func areEqualImages(img1: UIImage, img2: UIImage) -> Bool {

   guard let data1 = UIImagePNGRepresentation(img1) else { return false }
   guard let data2 = UIImagePNGRepresentation(img2) else { return false }

   return data1.isEqualToData(data2)
}

I hope this help you.

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
  • 2
    For swift 4 replace UIImagePNGRepresentation(img1) with data1 = image.pngData or data1 = image.jpegData(compressionQuality: 0.7) – Jeremy Andrews Jan 26 '19 at 07:53
  • 1
    I don't know why this happens and not sure I am completely correct but this will return NO if both images are empty images (eg initialised with no data). Even comparing the same instance to itself will return NO. – Artium Dec 18 '19 at 11:25
  • same thing happed with me – Yogesh Patel Mar 26 '20 at 05:41
14

You can convert your UIImage instances to NSData instances and compare them.

if let emptyImage = UIImage(named: "empty") {
    let emptyData = UIImagePNGRepresentation(emptyImage)
    let compareImageData = UIImagePNGRepresentation(image1.image)

    if let empty = emptyData, compareTo = compareImageData {
        if empty.isEqualToData(compareTo) {
            // Empty image is the same as image1.image
        } else {
            // Empty image is not equal to image1.image
        }
    } else {
        // Creating NSData from Images failed
    }
}
aahrens
  • 5,522
  • 7
  • 39
  • 63
  • 4
    In case someone is looking at this for Swift 3: `isEqualToData` does not exist anymore, instead, you can just use the `==` operator between 2 `Data` objects directly, just like any other 2 variables of the same type. – Marwan Alani Mar 11 '17 at 23:35