-2

我是这项技术的新手。我搜索了很多,但找不到任何相关的。在我的应用程序中,我从 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中显示它。

4

6 回答 6

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];
于 2012-06-15T14:00:39.893 回答
1
#import "NSDataAdditions.h"

NSData *dataObj = [NSData dataWithBase64EncodedString:StringImage];
UIImage *Image = [UIImage imageWithData:dataObj];
于 2012-06-19T06:41:56.483 回答
1

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

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

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

(由于这个原因,Apurv 的方法更直接,也更好。但由于你对它有这么大的困难,我想我会建议一种稍微不同的方法。)

于 2012-06-20T20:19:26.843 回答
0

您需要先对数据进行 Base64 解码。从许多 SOAP Web 服务返回的数据是 base 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];

那应该这样做。在我以前的经验中,我只是将我通过 web 服务获得的任何数据 blob 放入一个字符串中,然后使用这种方法创建图像,它工作得很好,这里有一个关于 Base64 编码和解码细节的精彩讨论:http://cocoadev .com/wiki/BaseSixtyFour这是我用来创建我的课程的,但 Nick 在 gitHub 上的代码更好,因为它符合 ARC。

于 2012-06-19T05:32:22.743 回答
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];
}

隐蔽NSDataUIImage

UIImage *imageOrig = [UIImage imageWithData:data];

我们也从NSData.

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

if (error1 != nil) {
    NSLog(@"Error parsing JSON.");
} else {
    NSLog(@"Array: %@", jsonArray);
}
于 2017-08-02T07:11:22.277 回答
-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);

也许它会帮助你...

于 2012-06-15T14:27:30.570 回答