UIImage is equal to

前端 未结 3 925
南笙
南笙 2021-01-14 11:17

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.

相关标签:
3条回答
  • 2021-01-14 11:47

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

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

    This also enables the != operator on UIImage.

    0 讨论(0)
  • 2021-01-14 12:02

    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.

    0 讨论(0)
  • 2021-01-14 12:06

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题