NSString to NSData conversion Problem
I have some Bytes of image in my string and i want to draw it to UIImageView ...Here is my code
NSString* str= @"<89504e47 0d0a1a0a 0000000d 49484452 ........... 454e44ae 426082>";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"My NSDATA %@",data);
imageView.image=[UIImage imageWithData:data];
Now when i saw that printed data on console it is not in same format what i gave to that string..The output is something like.....
<3c383935 30346534 37203064 30613161..........
开发者_C百科
So my imageview show nothing..... please help
if question was: How to convert string data to image then this is answer.
NSData *imgData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"]];
// set your string data into inputString var
NSString *inputString = [imgData description];
NSLog(@"input string %@",inputString);
// clearing string from trashes
NSString *dataStr = [inputString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
// separate by words of 4 bytes
NSArray *words = [dataStr componentsSeparatedByString:@" "];
// calculate number of bytes
NSArray *sizes = [words valueForKey:@"length"];
int sizeOfBytes = 0;
for (NSNumber *size in sizes) {
sizeOfBytes += [size intValue]/2;
}
int bytes[sizeOfBytes];
int counts = 0;
for (NSString *word in words) {
// convert each word from string to int
NSMutableString *ostr = [NSMutableString stringWithCapacity:[word length]];
while ([word length] > 0) {
[ostr appendFormat:@"%@", [word substringFromIndex:[word length] - 2]];
word = [word substringToIndex:[word length] - 2];
}
NSScanner *scaner = [NSScanner scannerWithString:ostr];
unsigned int val;
[scaner scanHexInt:&val];
bytes[counts] = val;
counts++;
}
// get NSData form c array
NSData* data = [NSData dataWithBytes:bytes length:sizeOfBytes];
NSLog(@"My NSDATA %@",data);
// your image is ready
UIImage *image = [UIImage imageWithData:data];
NSLog(@"image: %@",image);
what you are seeing in NSLog output are the ASCII codes of the string characters. for example:
NSString* str = @"A";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",data);
you will see something like:
<41....
that's because 0x41 is the code for letter A.
Same is happening with your string.
The data is exactly what you're feeding it: a simple string (printed as raw byte values). But I guess your input string is a hexdump and you manually need to turn into bytes.
精彩评论