我正在使用一个网络服务,它为我提供了一个整数数组形式的图像。我已设法将此数组转换为 NSData
对象,然后使用下面的代码转换为 UIImage
。
现在我不确定如何将图像转换为类似的数组。
数组看起来像这样:
[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,96,0,96,0,0,255,219,0,67,0,8,6,6,7,6,5,8,7,7,7,9,9,8,10,12,...]
这是我用来将上述数组转换为 UIImage
的代码。
+ (UIImage *)imageFromBytes:(NSArray *)bytes
{
unsigned char *buffer = (unsigned char *) malloc(bytes.count);
int i = 0;
for (NSDecimalNumber *num in bytes)
buffer[i++] = num.intValue;
NSData *data = [NSData dataWithBytes:buffer length:bytes.count];
free(buffer);
return [UIImage imageWithData:data];
}
因此,我需要将 UIImage
转换为整数数组(字节数组)。
有人能指出我正确的方向吗?
最佳答案
您可以通过以下方式获取图像的数据:
UIImage *image = [UIImage imageNamed:@"image.png"];
NSData *data = UIImagePNGRepresentation(image);
如果您使用 JPG,则可以使用 UIImageJPEGRepresentation。
然后,提取字节数组:
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
free(byteData)
您还可以使用 NSData 中的方法 (void)getBytes:(void *)buffer length:(NSUInteger)length
:
[data getBytes:&byteData length:len];
关于iphone - NSData 到字节数组(或整数数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10402834/