Jean-Luc Godard
Jean-Luc Godard

Reputation: 1883

How to show image from the Hex string [iphone]?

I have such Hex code 89504e470d0a1a0a0000000d49484452000001000000010008060000005c72a8

now this hex code is the code of some image . that I know , now I want to show that image in a imageView . I dont know how to do it because when I am converting this Hex into NSData and trying yo convert that data into image view and when I show that Image . the image is not being shown.

can anybody tell me how to do this?

// This is the first part i.e. image to hex conversion

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);

Upvotes: 1

Views: 1257

Answers (1)

Andrey Zverev
Andrey Zverev

Reputation: 4428

If I correctly understand your question, UIImage *image = [UIImage imageWithData:data]; is what you need.

Your NSData to hex conversion is incorrect, you're only taking first 8 bytes as hex token; use following code instead:

- (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;
}

Converting hex string back to 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];
}

Upvotes: 2

Related Questions