NSString to UIImage

本文解决从GTalk服务器下载的照片字符串转换为UIImage的问题,并提供将十六进制字符串转换为NSData的方法。

I am facing a problem to convert NSString to UIImage. EDIT1: I'm downloading photo as a string from gtalk server and parsed xml 5896efb83a92deaee41a30648cc9dbf7e9942b0e to use as an image.

 

 

It's not clear from the question what it is that you are trying to do.

There is no standard convention for storing pictures as strings, so you need to explain what format your [presence photo] returns.

For example, if the string contains the filename of the image, this is completely the wrong approach and you should load the image with initWithContentsOfFile. If it contains a base-64 encoded URL, you need to decode that into data using a Base64 decoding algorithm, etc.

If the string is just raw binary image data then this is a very weird thing to be doing because NSString is not intended for storing raw binary data and probably cannot be used in this way, but if it is what you are doing then the data most likely needs to be converted using UTF16 rather than UTF8, as that's the natural internal encoding for NSStrings.

EDIT: from your follow-up edit, it looks like your string is hex encoded, so you'll need to convert it to data using a hex decoder. There's an answer about how to do this here:

Convert hex data string to NSData in Objective C (cocoa)

After that, you may still need to do further processing, depending on what format the data is in (e.g. PNG versus JPEG), but try passing the decoded data to intWithData and see how you get on.

 

 

Convert hex data string to NSData in Objective C (cocoa)

fairly new iPhone developer here. Building an app to send RS232 commands to a device expecting them over a TCP/IP socket connection. I've got the comms part down, and can send ASCII commands fine. It's the hex code commands I'm having trouble with.

So lets say I have the following hex data to send (in this format):

\x1C\x02d\x00\x00\x00\xFF\x7F

How do I convert this into an NSData object, which my send method expects?

Obviously this does not work for this hex data (but does for standard ascii commands):

NSString*commandascii;
NSData*commandToSend;
commandascii
=@"\x1C\x02d\x00\x00\x00\xFF\x7F";
commandToSend
=[commandascii dataUsingEncoding:NSStringEncoding];

For a start, some of the \x hex codes are escape characters, and I get an "input conversion stopped..." warning when compiling in XCode. And NSStringEncoding obviously isn't right for this hex string either.

So the first problem is how to store this hex string I guess, then how to convert to NSData.

 

 

Code for hex in NSStrings like "00 05 22 1C EA 01 00 FF". 'command' is the hex NSString.

command =[command stringByReplacingOccurrencesOfString:@" " withString:@""];
NSMutableData*commandToSend=[[NSMutableData alloc] init];
unsignedchar whole_byte;
char byte_chars[3]={'\0','\0','\0'};
int i;
for(i=0; i <8; i++){
    byte_chars
[0]=[command characterAtIndex:i*2];
    byte_chars
[1]=[command characterAtIndex:i*2+1];
    whole_byte
= strtol(byte_chars, NULL,16);
   
[commandToSend appendBytes:&whole_byte length:1];
}
NSLog(@"%@", commandToSend);






If you can hard code the hex data:

constchar bytes[]="\x00\x12\x45\xAB";
size_t length
=(sizeof bytes)-1;//string literals have implicit trailing '\0'

NSData*data =[NSData dataWithBytes:bytes length:length];

If your code must interpret the hex string (assuming the hex string is in a variable called inputDataand lengthOfInputData is the length of inputData):


#defineHexCharToNybble(x)((char)((x >'9')? tolower(x)-'a'+10: x -'0')&0xF)

int i;

NSMutableData*data =[NSMutableData data];

for(i =0; i < lengthOfInputData;)
{
   
char byteToAppend;

   
if(i <(lengthOfInputData -3)&&
        inputData
[i+0]=='\\'&&
        inputData
[i+1]=='x'&&
        isxdigit
(inputData[i+2])&&
        isxdigit
(inputData[i+3]))
   
{
        byteToAppend
=HexCharToNybble(inputData[i+2])<<4+HexCharToNybble(input[i+3]);
        i
+=4;
   
}
   
else
   
{
        byteToAppend
= inputData[i];
        i
+=1;
   
}

   
[data appendBytes:&byteToAppend length:1];
}



Woah, that's ugly. Sorry if I have blinded anyone with that source code. It kinda looked ugly as I was writing it but decided to finish it anyway. 
Also, completely untested. 



Here's an example decoder implemented on a category on NSString.

 
 
#import <stdio.h>
#import <stdlib.h>
#import <string.h>

unsignedchar strToChar (char a,char b)
{
   
char encoder[3]={'\0','\0','\0'};
    encoder
[0]= a;
    encoder
[1]= b;
   
return(char) strtol(encoder,NULL,16);
}

@interfaceNSString(NSStringExtensions)
-(NSData*) decodeFromHexidecimal;
@end

@implementationNSString(NSStringExtensions)

-(NSData*) decodeFromHexidecimal;
{
   
constchar* bytes =[self cStringUsingEncoding: NSUTF8StringEncoding];
   
NSUInteger length = strlen(bytes);
   
unsignedchar* r =(unsignedchar*) malloc(length /2+1);
   
unsignedchar* index = r;

   
while((*bytes)&&(*(bytes +1))){
       
*index = strToChar(*bytes,*(bytes +1));
        index
++;
        bytes
+=2;
   
}
   
*index ='\0';

   
NSData* result =[NSData dataWithBytes: r length: length /2];
    free
(r);

   
return result;
}

@end
Thanks xyzzy, though this doesn't compile - it has issues with safeMalloc, strToChar and safeStrLen. Do I need to include/import something for these functions to work?

h, right. You can replace these calls w/ malloc and strlen. I'll update the response.
Should compile now.




f I want to hard-code the bytes, I do something like this:
enum{ numCommandBytes =8};
staticconstunsignedchar commandBytes[numCommandBytes]={0x1c,0x02,'d',0x0,0x0,0x0,0xff,0x7f};

If you're obtaining these backslash-escaped bytes at run time, try the strunvis function.

Obviously this does not work for this hex data (but does for standard ascii commands):

NSString*commandascii;
NSData*commandToSend;
commandascii
=@"\x1C\x02d\x00\x00\x00\xFF\x7F";
commandToSend
=[commandascii dataUsingEncoding:NSStringEncoding];

For a start, some of the \x hex codes are escape characters, and I get an "input conversion stopped..." warning when compiling in XCode. And NSStringEncoding obviously isn't right for this hex string either.

First, it's Xcode, with a lowercase c.

Second, NSStringEncoding is a type, not an encoding identifier. That code shouldn't compile at all.

More to the point, backslash-escaping is not an encoding; in fact, it's largely independent of encoding. The backslash and 'x' are characters, not bytes, which means that they must be encoded to (and decoded from) bytes, which is the job of an encoding.

 

 

 

 

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值