2013-08-19 28 views
7

我使用如何将UIImage序列化为JSON?

imageData = UIImagePNGRepresentation(imgvw.image);

,并同时发布

[dic setObject:imagedata forKey:@"image"]; 

NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&theError];

现在应用程序崩溃终止应用程序由于未捕获的异常 'NSInvalidArgumentException',究其原因: 'JSON写入中的无效类型(NSConcreteMutab leData)

+2

看看这里 - > http://www.json.org/看来你需要更多地了解JSON您尝试使用前它。本页面的关键部分是**值**部分。查看JSON标准允许的各种值。 – borrrden

+0

什么是您在字典中设置的图像日期? –

+0

我很确定你使用错误的字典。你在哪里分配了字典,什么是imagedate? –

回答

11

您需要将您的UIImage转换为NSData的,然后再转换该NSData的到NSString这将是你的数据的base64字符串表示。

一旦你的NSData *获得的NSString *,你可以把它在关键@“图像”

要的NSData转换为一个base64类型的NSString添加到您的字典*请参阅以下链接: How do I do base64 encoding on iphone-sdk?

在多个伪方式的过程中会这个样子

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"); 
    } 
+0

谢谢你的工作...... – user2181966

+0

很高兴认识这个.. – CodenameLambda1

-3

您可以在TI的NSData转换您的图片,如: -

如果PNG图像

UIImage *image = [UIImage imageNamed:@"imageName.png"]; 
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)]; 

如果JPG图像

UIImage *image = [UIImage imageNamed:@"imageName.jpg"]; 
NSData *imageData = UIImageJPEGRepresentation(image, 1.0); 

,你可以存储它到CoreData可能就像这样对你有用: -

[newManagedObject setValue:imageData forKey:@"image"]; 

您可以加载,如: -

NSManagedObject *selectedObject = [[self yourFetchCOntroller] objectAtIndexPath:indexPath]; 
     UIImage *image = [UIImage imageWithData:[selectedObject valueForKey:@"image"]]; 
// and set this image in to your image View 
    yourimageView.image=image; 
+3

问题标题有误导性。问题是如何通过JSON发送图像。我看不出如何在Core Data中保存图像。 –

4

试试这个

​​

const unsigned char *bytes = [imageData bytes]; 
NSUInteger length = [imageData length]; 
NSMutableArray *byteArray = [NSMutableArray array]; 
for (NSUInteger i = 0; i length; i++) 
{ 
    [byteArray addObject:[NSNumber numberWithUnsignedChar:bytes[i]]]; 
} 

NSDictionary *dictJson = [NSDictionary dictionaryWithObjectsAndKeys: 
       byteArray, @"photo", 
       nil]; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictJson options:0 error:NULL];