Objective-C:将图像与之前保存的另一张图像进行比较

标签 objective-c ios memory uiimage compare

当一个图像已经使用 NSSearchPathForDirectoriesInDomains 方法通过保存和加载过程时,我有一个关于在 Objective-C 中比较 UIImages 的问题。

我想要的目的是根据图像显示的内容在点击时将用户引导至新屏幕。

为简单起见,假设有两种可能性 - 黑色图像和绿色图像。单击黑色图像会将您带到 xib1,单击绿色图像会将您带到 xib2。

这很简单,并且一直有效,直到我实现了保存和加载系统。

为了保存,我执行以下操作:

paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
pngFilePath = [NSString stringWithFormat:@"%@/test.png",documentsDirectory];
data1 = [NSData dataWithData:UIImagePNGRepresentation([level1part1 objectAtIndex:0])];
[data1 writeToFile:pngFilePath atomically:YES];

并加载我执行以下操作:

paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
pngFilePath = [NSString stringWithFormat:@"%@/test.png",documentsDirectory];
UIImage *image = [UIImage imageWithContentsOfFile:pngFilePath];
[button1 setImage:image forState:UIControlStateNormal];

这很好,当我退出程序并重新启动它时,图像会按我希望的方式保留在屏幕上。假设现在出现在 button1 上的图像是绿色图像。

当我点击带有发件人 id 的按钮(这是 button1)后调用以下代码时:

if(sender.currentImage == [UIImage imageNamed:self.greenImage])
{
    VisitAlreadyCorrectScreen *screen = [[VisitAlreadyCorrectScreen alloc] initWithNibName:nil bundle:nil];
    screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:screen animated:YES];
}

即使 currentImage 是绿色图像并且与我正在比较的绿色图像相同,我认为因为我在保存过程中将绿色图像保存到内存中,所以比较不起作用,因为它们被保存在内存中的不同位置 - 由以下 NSLog 验证:

Current Image: <UIImage: 0x95614c0>, and Yes Image: <UIImage: 0xde748f0>

我不知道如何比较这两个图像,以便在这种情况下它们匹配(它们都与我在资源文件夹中的同一个图像相关)。有没有人有任何建议?

如果我没有很好地解释问题是什么,请告诉我!

提前致谢!

最佳答案

如果是从网上下载的,可以比较图片名称或图片网址,也比比较图片要快。

另外,问题在于,通过使用 == 运算符,您正在比较图像 0x95614c0 和 0xde748f0 的内存地址。这就是为什么不相等。您是在比较它们是否是同一个对象,而不是图像是否相等。

比较图像使用:如 Fls'Zen 回答中所述。

if ([UIImagePNGRepresentation(blackImage) isEqualToData:UIImagePNGRepresentation(greenImage)])

关于Objective-C:将图像与之前保存的另一张图像进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11216167/

相关文章:

C 程序怪异行为——指针和内存

linux - CentOS内存使用异常

iphone - 通过 ASIHTTP 请求并行下载文件的最大数量

iphone - IOS7中的图像背景问题

ios - iOS。 discoverCharacteristics方法调用SIGABRT信号

ios - Apple Mach-O 链接器错误 - 体系结构 x86_64 : "_UISceneWillEnterForegroundNotification" and "___isPlatformVersionAtLeast" 的 undefined symbol

ios - 如何创建像 Vine App 一样的下拉表格 View

c# - 如何更改 map 标题 iOS Xamarin 中的字体大小(C#)

ios - 如何将可选 View 传递给 SwiftUI 中的另一个 View ?

java - 如何解决嵌套ArrayList的StackOverflowError?