gpt4 book ai didi

iphone - 将二进制图像数据从 Web 服务读取到 UIImage 中

转载 作者:行者123 更新时间:2023-12-03 19:11:07 25 4
gpt4 key购买 nike

我正在 iPhone 应用程序中使用 Web 服务。 Web 服务方法返回一个包含多个字段(例如 ID、描述等)的响应。其中一个字段包含二进制图像数据,我需要在 iPhone 应用程序中将其转换为 UIImage。

我正在成功使用 NSXMLParser 从 XML 响应中提取数据。在 XMLParser 的 parser:foundCharacters: 选择器中,它给出了一个指向每个字段中的字符串的 NSString*。由于这是一个字符串,因此当我遇到图像字段时,我会执行以下操作来读取图像数据:

UIImage *img = [[UIImage alloc] initWithData:[string dataUsingEncoding:NSUTF8StringEncoding]];

但是 img 变量在这行之后仍然是“nil”。似乎 XML 字符串中的数据不兼容转换。我在这里做错了什么? (我能够将其他字段读入我的变量,但不能读取此图像数据字段)

提前致谢..

最佳答案

根据 fbrereto 的回答,我设法使用此链接中的代码示例将字符串转换为 NSData:http://www.cocoadev.com/index.pl?BaseSixtyFour(滚动到 MiloBird 用户的代码示例)。现在我可以成功构建图像了。

它使用 Objective-C 类别将选择器 + (id)dataWithBase64EncodedString:(NSString *)string; 添加到 NSData 类。这是我从上面的链接中提取的必要代码示例:

//MBBase64.h

@interface NSData (MBBase64)

+ (id)dataWithBase64EncodedString:(NSString *)string; // Padding '=' characters are optional. Whitespace is ignored.

@end


//MBBase64.m

static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation NSData (MBBase64)

+ (id)dataWithBase64EncodedString:(NSString *)string;
{
if (string == nil)
[NSException raise:NSInvalidArgumentException format:nil];
if ([string length] == 0)
return [NSData data];

static char *decodingTable = NULL;
if (decodingTable == NULL)
{
decodingTable = malloc(256);
if (decodingTable == NULL)
return nil;
memset(decodingTable, CHAR_MAX, 256);
NSUInteger i;
for (i = 0; i < 64; i++)
decodingTable[(short)encodingTable[i]] = i;
}

const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
if (characters == NULL) // Not an ASCII string!
return nil;
char *bytes = malloc((([string length] + 3) / 4) * 3);
if (bytes == NULL)
return nil;
NSUInteger length = 0;

NSUInteger i = 0;
while (YES)
{
char buffer[4];
short bufferLength;
for (bufferLength = 0; bufferLength < 4; i++)
{
if (characters[i] == '\0')
break;
if (isspace(characters[i]) || characters[i] == '=')
continue;
buffer[bufferLength] = decodingTable[(short)characters[i]];
if (buffer[bufferLength++] == CHAR_MAX) // Illegal character!
{
free(bytes);
return nil;
}
}

if (bufferLength == 0)
break;
if (bufferLength == 1) // At least two characters are needed to produce one byte!
{
free(bytes);
return nil;
}

// Decode the characters in the buffer to bytes.
bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);
if (bufferLength > 2)
bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);
if (bufferLength > 3)
bytes[length++] = (buffer[2] << 6) | buffer[3];
}

realloc(bytes, length);
return [NSData dataWithBytesNoCopy:bytes length:length];
}

@end

谢谢大家!

关于iphone - 将二进制图像数据从 Web 服务读取到 UIImage 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2360986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com