如何显示十六进制字符串[iphone]中的图像?

时间:2011-12-08 12:49:22

标签: iphone uiimage hex nsdata

I have such Hex code 89504e470d0a1a0a0000000d49484452000001000000010008060000005c72a8

现在这个十六进制代码是一些图像的代码。我知道,现在我想在imageView中显示该图像。我不知道该怎么做,因为当我将这个Hex转换为NSData并尝试将该数据转换为图像视图时以及当我显示Image时。图像未显示。

谁能告诉我怎么做?

//这是第一部分,即图像到十六进制转换

UIImage *img = [UIImage imageNamed:@"image.png"];
NSData *data1 = UIImagePNGRepresentation(img);

// NSLog(@“data is%@”,data1);

const unsigned *tokenBytes = [data1 bytes];
NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                      ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                      ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                      ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];

NSLog(@"hexToken is %@",hexToken);

1 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,UIImage *image = [UIImage imageWithData:data];就是您所需要的。

您的NSData到十六进制转换不正确,您只将前8个字节作为十六进制令牌;请改用以下代码:

- (NSString*)stringWithHexBytes:(NSData *) data {
    static const char hexdigits[] = "0123456789ABCDEF";
    const size_t numBytes = [data length];
    const unsigned char* bytes = [data bytes];
    char *strbuf = (char *)malloc(numBytes * 2 + 1);
    char *hex = strbuf;
    NSString *hexBytes = nil;

    for (int i = 0; i<numBytes; ++i) {
        const unsigned char c = *bytes++;
        *hex++ = hexdigits[(c >> 4) & 0xF];
        *hex++ = hexdigits[(c ) & 0xF];
    }
    *hex = 0;
    hexBytes = [NSString stringWithUTF8String:strbuf];
    free(strbuf);
    return hexBytes;
}

将十六进制字符串转换回NSData:

- (NSData *) hexStringToData:(NSString *) hexString
{
    unsigned char whole_byte;
    NSMutableData *returnData= [[NSMutableData alloc] init];
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < 8; i++) {
        byte_chars[0] = [hexString characterAtIndex:i*2];
        byte_chars[1] = [hexString characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [returnData appendBytes:&whole_byte length:1]; 
    }
    return (NSData *) [returnData autorelease];
}