2 atto Atto_ 于 2014.08.08 12:24 提问

如何计算位于iOS相册中图片的正确md5值

具体情况

在OS X下,计算得的正确md5值是:63e3fbe6 a0438f26 e49e5dab 1c4af0d3。

NSData *temp = [[NSData alloc] initWithContentsOfFile:@"/Users/apple/Pictures/temp/tu7.png"];
NSLog(@"md5: %@", [temp md5]);

在iOS中,UIImagePickerControllerDelegate协议,imagePickerController: didFinishPickingMediaWithInfo:方法,计算的的md5值是:55ea2f62 5df31067 683aa9a8 3a06d420。

UIImage *image = info[UIImagePickerControllerOriginalImage];
NSData *temp = UIImagePNGRepresentation(image);
NSLog(@"md5: %@", [temp md5]);

两个md5值结果不一样,我希望计算图片整个文件的md5,因为要拿这个md5值与服务器上贮存的图片进行比对,服务器上图片文件计算得md5与通过绝对路径计算得md5相同,所以我尝试获取被选中图片的路径,像/Users/apple/Pictures/temp/tu7.png这种形式的,我知道通过info可以获取asset library url。

NSURL *imgurl = [info objectForKey:UIImagePickerControllerReferenceURL];

获得的结果是像assets-library://asset/asset.JPG?id=00000000-0000-0000-0000-00000000007E&ext=JPG这种形式的。

  1. 有什么方法可以把asset library url变成绝对路径,也就是 形式assets-library://asset/asset.JPG?id=00000000-0000-0000-0000-00000000007E&ext=JPG -> 形式/Users/apple/Pictures/temp/tu7.png 的转变?
  2. 如果没有,有什么方法可以决解这个问题?能否提供提供决解思路?

1个回答

weixin_36809389
weixin_36809389   2016.11.24 14:54
  • (NSString *)fileMD5WithAsset:(ALAsset *)asset
    {
    if (!asset) {
    return nil;
    }

    ALAssetRepresentation *rep = [asset defaultRepresentation];
    unsigned long readStep = 256;
    uint8_t *buffer = calloc(readStep, sizeof(*buffer));
    unsigned long long offset = 0;
    unsigned long long bytesRead = 0;
    NSError *error = nil;
    unsigned long long fileSize = [rep size];
    int chunks = (int)((fileSize + readStep - 1)/readStep);
    unsigned long long lastChunkSize = fileSize%readStep;

    CC_MD5_CTX md5;
    CC_MD5_Init(&md5);
    BOOL isExp = NO;
    int currentChunk = 0;
    while(!isExp && currentChunk < chunks){
    @try {
    if(currentChunk < chunks - 1){
    bytesRead = [rep getBytes:buffer fromOffset:offset length:(unsigned long)readStep error:&error];
    }else{
    bytesRead = [rep getBytes:buffer fromOffset:offset length:(unsigned long)lastChunkSize error:&error];
    }
    NSData * fileData = [NSData dataWithBytesNoCopy:buffer length:(unsigned long)bytesRead freeWhenDone:NO];
    CC_MD5_Update(&md5, [fileData bytes], (CC_LONG)[fileData length]);
    offset += readStep;
    } @catch(NSException exception) {
    isExp = YES;
    free(buffer);
    }
    currentChunk += 1;
    }
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &md5);
    NSString
    s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
    digest[0], digest[1],
    digest[2], digest[3],
    digest[4], digest[5],
    digest[6], digest[7],
    digest[8], digest[9],
    digest[10], digest[11],
    digest[12], digest[13],
    digest[14], digest[15]];
    return s;
    }

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!