从 NSData 计算 iPhone 上的校验和
使用 iPhone SDK,我让用户从图像选择器中选择图像。 如果用户选择了他们之前选择过的图像,我想让用户意识到这一点。
我最初的计划(只是为了确保其他事情现在有效)是将图像保存到文件中(出于其他原因无论如何都需要这样做),使用 NSData 的校验和作为文件名。 然后,当他们稍后选择相同的图像时,校验和将相同,因此我可以看到具有该名称的文件已经存在 - 欢呼!
不过,我已经在互联网和 Apple 文档中搜索了如何从 NSData 计算校验和。 我知道我可以实现自己的实现,但如果可能的话,我宁愿避免这种情况。 我也很高兴了解如何检查两个 UIImage 是否相同的其他想法。
编辑
两年前,我承诺提供一个代码示例,现在就是这样。 真的很抱歉耽误了! :)
+(NSString*)imageIdForData:(NSData*)data
{
char* result = (char*) [[data MD5Sum] bytes];
NSString* hash = [NSString stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1],
result[2], result[3],
result[4], result[5],
result[6], result[7],
result[8], result[9],
result[10], result[11],
result[12], result[13],
result[14], result[15]];
return hash;
}
Using the iPhone SDK, I'm having the user select images from the image picker. If the user selects an image they've selected before, I'd like to make the user aware of it.
My initial plan (just to make sure other things work for now) is to save the image to a file (need to do this anyway for other reasons), using a checksum of the NSData as the filename. Then, when they select the same image later on, the checksum will be the same and so I can see that a file with that name already exists - hurrah!
However, I've scoured the internet and the Apple docs for how to compute a checksum from a NSData. I know I could implement my own implementation, but I'd prefer to avoid that, if possible. I'm also happy for other ideas of how to check that two UIImages are the same.
EDIT
Two years ago I promised a code sample, and here it is. Really sorry for the delay! :)
+(NSString*)imageIdForData:(NSData*)data
{
char* result = (char*) [[data MD5Sum] bytes];
NSString* hash = [NSString stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1],
result[2], result[3],
result[4], result[5],
result[6], result[7],
result[8], result[9],
result[10], result[11],
result[12], result[13],
result[14], result[15]];
return hash;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为有了类别,一切都变得更好......
标题:
实施:
Because everything is better with categories...
Header:
Implementation:
在
头文件中应该有一个 CC_MD5 函数,用于计算任意数据的 MD5 哈希值。 它是一个 C 函数,因此它不能直接在 NSData 上工作,但它应该可以满足您的需要。更多信息(包括使用 NSString 的包装器 - 应该是很容易转换为使用 NSData)
In the
<CommonCrypto/CommonDigest.h>
header file there should be a CC_MD5 function that will compute an MD5 hash of arbitrary data. It's a C function, so it won't work directly on an NSData, but it should do what you need.Some more info here (including a wrapper using NSString - should be easy enough to convert to use NSData)