Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage is equal to

Tags:

swift

uiimage

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.

like image 916
Murat Kaya Avatar asked Jan 12 '16 19:01

Murat Kaya


1 Answers

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.

like image 116
Cristik Avatar answered Oct 21 '22 04:10

Cristik