字节数组到NSData [英] Byte Array to NSData

查看:172
本文介绍了字节数组到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 class

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];

然后遍历字符串数组,将每个条目转换为整数,并将其添加到已分配的字节指针/ array:

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,然后使用init初始化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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆