Comparing UIImage

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

How can I compare an image to another one?

Thanks!

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 21:00

    This is what I use in my unit tests to compare images. Unlike other methods (e.g., UIImagePNGRepresentation), it works even if the images have a different color space (e.g., RGB and grayscale).

    @implementation UIImage (HPIsEqualToImage)
    
    - (BOOL)hp_isEqualToImage:(UIImage*)image
    {
        NSData *data = [image hp_normalizedData];
        NSData *originalData = [self hp_normalizedData];
        return [originalData isEqualToData:data];
    }
    
    - (NSData*)hp_normalizedData
    {
        const CGSize pixelSize = CGSizeMake(self.size.width * self.scale, self.size.height * self.scale);
        UIGraphicsBeginImageContext(pixelSize);
        [self drawInRect:CGRectMake(0, 0, pixelSize.width, pixelSize.height)];
        UIImage *drawnImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return UIImagePNGRepresentation(drawnImage);
    }
    
    @end
    

    It's not very efficient, so I would recommend against using it in production code unless performance is not an issue.

提交回复
热议问题