字节数组到 NSData [英] Byte Array to NSData
问题描述
WebService JSON 响应即将到来.在响应中,图像以字节数组的形式出现.我必须在 UIImageView 中显示图像.我正在尝试将字节数组转换为 NSData.但不知道如何做到这一点.任何帮助,将不胜感激.我相信字节数组中包含图像数据.示例字节数组供您参考:
In a WebService JSON response is coming. In the response, there is image is coming as a byte array. I have to show the image in a UIImageView. I am trying to convert the byte array to NSData. But not getting how to do that. Any help would be appreciated. I am confident that the byte array has image data in it. Sample Byte array for your reference:
(137,
80,
78,
71,
...
66,
96,
130)
谢谢
推荐答案
您必须先将 JSON 转换为字符串数组;例如,您可以使用 NSJSONSerialization
班级:
You have to convert the JSON to an array of strings first; you can, for example, use the NSJSONSerialization
class:
NSArray *strings = [NSJSONSerialization JSONObjectWithData:theJSONString options:kNilOptions error:NULL];
然后遍历字符串数组,将每个条目转换为整数,并将其添加到分配的字节指针/数组中:
Then walk the strings array, convert each entry to an integer, and add it to an allocated byte pointer/array:
unsigned c = strings.count;
uint8_t *bytes = malloc(sizeof(*bytes) * c);
unsigned i;
for (i = 0; i < c; i++)
{
NSString *str = [strings objectAtIndex:i];
int byte = [str intValue];
bytes[i] = byte;
}
然后最后从字节中生成一个 NSData,然后使用它初始化一个 UIImage 对象:
Then finally make an NSData out of the bytes, then init an UIImage object using it:
NSData *imageData = [NSData dataWithBytesNoCopy:bytes length:c freeWhenDone:YES];
UIImage *image = [UIImage imageWithData:imageData];
这篇关于字节数组到 NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!