1

好的,我正在对图像进行哈希处理。众所周知,散列图像需要FOREVER。所以我要抽取 100 个图像样本,均匀分布。这是代码。

#define NUM_HASH_SAMPLES 100

@implementation UIImage(Powow)

-(NSString *)md5Hash
{
    NSData *data = UIImagePNGRepresentation(self);

    char *bytes = (char*)malloc(NUM_HASH_SAMPLES*sizeof(char));
    for(int i = 0; i < NUM_HASH_SAMPLES; i++)
    {
        int index = i*data.length/NUM_HASH_SAMPLES;

        bytes[i] = (char)(data.bytes[index]); //Operand of type 'const void' where arithmetic or pointer type is required
    }

    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( bytes, NUM_HASH_SAMPLES, result );
    return [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]
            ];
}

错误在注释行上。

我究竟做错了什么?

4

2 回答 2

4

data.bytes是 a void *,因此取消引用它(甚至对其执行必要的指针运算)是没有意义的。

因此,如果您打算从数据中取出一个字节,那么获取一个指向const unsigned char并取消引用它的指针:

const unsigned char *src = data.bytes;
/* ..then, in your loop.. */
bytes[i] = src[index];

哦,不要将返回值转换为malloc()!

于 2013-08-27T08:48:22.330 回答
1

根据 NSData 的文档,data.bytes返回类型为const void *. 基本上,您正在尝试访问一个void没有意义的指针,因为void它没有大小。

将其转换为 char 指针并取消引用它。

((const char *)data.bytes)[index]

或者

*((const char *)data.bytes + index)

编辑:我通常会立即将指针分配给已知数据类型并使用它。

IE

const char *src = data.bytes;
bytes[i] = src[index];

Edit2:您可能还希望按照constH2CO3 的建议保留限定符。这样你就不会不小心写到你不应该写的位置。

于 2013-08-27T08:50:32.900 回答