我的字符串中有一些字节的图像,我想将它绘制到UIImageView ...这是我的代码
NSString* str= @"<89504e47 0d0a1a0a 0000000d 49484452 ........... 454e44ae 426082>";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"My NSDATA %@",data);
imageView.image=[UIImage imageWithData:data];
现在,当我在控制台上看到打印数据时,它与我给该字符串的格式不同。输出类似......
<3c383935 30346534 37203064 30613161..........
所以我的imageview什么都没显示.....请帮忙
答案 0 :(得分:2)
如果问题是:如何将字符串数据转换为图像,那么这就是答案。
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);
答案 1 :(得分:1)
您在NSLog输出中看到的是字符串字符的ASCII代码。 例如:
NSString* str = @"A";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",data);
你会看到类似的东西:
&LT; 41 ...
那是因为0x41是字母A的代码。
你的字符串也是如此。
答案 2 :(得分:0)
数据正好你正在提供它:一个简单的字符串(打印为原始字节值)。但我猜你的输入字符串是一个hexdump,你手动需要变成字节。