将来自Web服务的字节数组转换为UIImage iPhone

时间:2012-06-15 13:58:37

标签: iphone objective-c web-services

我是这项技术的新手。 我搜索了很多,但无法找到任何相关的。 在我的应用程序中,我从Web服务接收字节数组,我从Web服务收到的字节数组是

  

[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,1,195,0,0,1,195,8, 2,0,0,0,215,2 ...]

我希望将此字节数组转换为 UIImage ,以便在 UIImageView 中显示它。

6 个答案:

答案 0 :(得分:6)

使用下面的UIImage构造函数。

+ (UIImage *)imageWithData:(NSData *)data;

NSData *data = [NSData dataWithBytes:YOUR_BYTE_ARRAY length:ARRAY_LENGTH];

UIImage *img = [UIImage imageWithData:data];

UIImageView *imgView = [[UIImageView alloc]initWithImage:img];

答案 1 :(得分:1)

#import "NSDataAdditions.h"

NSData *dataObj = [NSData dataWithBase64EncodedString:StringImage];
UIImage *Image = [UIImage imageWithData:dataObj];

答案 2 :(得分:1)

上面的字节数组中的前8个字节\211 P N G \r \n \032 \n(或十进制的137,80,78,71,13,10,26,10)表明这是一个PNG文件。

至少,您应该只需将整个字节序列保存到文件中,然后使用+ (UIImage *)imageNamed:(NSString *)name+ (UIImage *)imageWithContentsOfFile:(NSString *)path加载它。例如:

  UIImage *myImage = [UIImage imageNamed:@"myfile.png"]
                                      // myfile.png should be in the main bundle

(Apurv的方法更直接,更好的原因。但是由于你遇到这样的困难,我认为我建议采用略有不同的方法。)

答案 3 :(得分:0)

您需要先对Base64进行数据解码。从许多SOAP Web服务返回的数据是基于64位编码的,有时是嵌入在网站中的原始数据。这很简单,但最容易使用其他人创建的库。

首先将其包含在您的项目中,并在此文件中包含.h:https://github.com/nicklockwood/Base64

NSString *base64String = @"**YOUR BYE ARRAY HERE**";
UIImage *imageOrig = [UIImage imageWithData:[NSData dataFromBase64String:base64String]];
UIImageView *imageView = [[UIImageView alloc]initWithImage:imageOrig];

应该这样做。在我以前的经验中,我只是把我通过webservice获得的数据blob放到一个字符串中,然后使用这个方法创建图像,它很有效,在这里对Base64编码和解码的细节进行了很好的讨论:http://cocoadev.com/wiki/BaseSixtyFour这是我用来创建我的类,但是在gitHub上的Nick代码因为它的ARC兼容性要好得多。

答案 4 :(得分:0)

从Webservice我们得到NSNumber数组。我们必须将其转换为NSData,如下所示:

NSMutableData *data = [[NSMutableData alloc] initWithCapacity: [strings count]];
for( NSNumber *number in strings) {
    char byte = [number charValue];
    [data appendBytes: &byte length: 1];
}

NSData隐藏到UIImage

UIImage *imageOrig = [UIImage imageWithData:data];

我们也从NSData获得了JSON。

NSError *error1 = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error1];

if (error1 != nil) {
    NSLog(@"Error parsing JSON.");
} else {
    NSLog(@"Array: %@", jsonArray);
}

答案 5 :(得分:-1)

  //Use this

CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
CGContextRef bitmapContext=CGBitmapContextCreate(YOUR_BYTE_ARRAY, w, h, 8, 4*w, colorSpace,  kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault);
CFRelease(colorSpace);
free(YOUR_BYTE_ARRAY);
CGImageRef cgImage=CGBitmapContextCreateImage(bitmapContext);
CGContextRelease(bitmapContext);

UIImage *newimage = [UIImage imageWithCGImage:cgImage];
[yourImageView setImage:newimage];
CGImageRelease(cgImage);

可能会帮助你...