Reputation: 5005
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.
NSString *myPicture = [presence photo]; NSData *pic = nil; if (![myPicture isEqualToString:@""]) { pic = [myPicture dataUsingEncoding:NSUTF8StringEncoding]; } UIImage *picture; NSLog(@"Photo %@", pic); if (pic == nil) { picture = [UIImage imageWithData:[Utils getAvatar]]; } else { picture = [UIImage imageWithData:pic]; } NSLog(@"Picture %@", picture);
The logs
Photo 35383936 65666238 33613932 64656165 65343161 33303634 38636339 64626637 65393934 32623065 Picture (null)
The part with
picture = [UIImage imageWithData:[Utils getAvatar]]works fine
Any idea?
Upvotes: 0
Views: 1601
Reputation: 1398
Hope helpful to you.
picture = [[UIImage alloc] initWithData:pic];
Upvotes: 0
Reputation: 40995
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.
Upvotes: 1