Comparing UIImage

前端 未结 4 1917
野趣味
野趣味 2020-11-27 20:38

How can I compare an image to another one?

Thanks!

4条回答
  •  难免孤独
    2020-11-27 21:10

    Update

    Based on Skycamelfalling's comment, I verified that my unit tests still pass when using UIImage's pngData() method, instead of drawing with an image context. Much simpler!

    For historic interest: Here is a Swift 4 variant of hpique's answer. It's working for me in my unit tests, when I need to test two UIImages for "sameness".

    fileprivate extension UIImage {
        func makeNormalizedData() -> Data? {
            defer { UIGraphicsEndImageContext() }
            let pixelSize = CGSize(width: size.width * scale, height: size.height * scale)
            UIGraphicsBeginImageContext(pixelSize)
            draw(in: CGRect(origin: CGPoint.zero, size: pixelSize))
            guard let drawnImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
            return UIImagePNGRepresentation(drawnImage)
        }
    }
    

提交回复
热议问题