如何将UIImage序列化为JSON? [英] How to serialize UIImage to JSON?
问题描述
我正在使用
imageData = UIImagePNGRepresentation(imgvw.image);
并且在发布时
[dic setObject:imagedata forKey:@"image"];
NSData * data = [NSJSONSerialization dataWithJSONObject:dic选项:NSJSONWritingPrettyPrinted错误:& theError];
现在应用程序崩溃终止应用程序由于未捕获的异常' NSInvalidArgumentException
',原因:'JSON写入中的类型无效(NSConcreteMutableData)
now app is crashing Terminating app due to uncaught exception 'NSInvalidArgumentException
', reason: 'Invalid type in JSON write (NSConcreteMutableData)
推荐答案
您需要将UIImage转换为NSData,然后将该NSData转换为NSString,它将是您数据的base64字符串表示形式。
You need to convert your UIImage to NSData and then convert that NSData to a NSString which will be base64 string representation of your data.
从NSData *获得NSString *后,您可以在密钥@image将其添加到您的字典中
Once you get the NSString* from NSData*, you can add it to your dictionary at key @"image"
要将NSData转换为base64类型NSString *,请参阅以下链接:
如何在iphone-sdk上进行base64编码?
To convert NSData to a base64 type NSString* refer to the following link: How do I do base64 encoding on iphone-sdk?
以更伪的方式处理看起来像这样
In a more pseudo-way the process will look like this
UIImage *my_image; //your image handle
NSData *data_of_my_image = UIImagePNGRepresentation(my_image);
NSString *base64StringOf_my_image = [data_of_my_image convertToBase64String];
//now you can add it to your dictionary
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:base64StringOf_my_image forKey:@"image"];
if ([NSJSONSerialization isValidJSONObject:dict]) //perform a check
{
NSLog(@"valid object for JSON");
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error!=nil) {
NSLog(@"Error creating JSON Data = %@",error);
}
else{
NSLog(@"JSON Data created successfully.");
}
}
else{
NSLog(@"not a valid object for JSON");
}
这篇关于如何将UIImage序列化为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!