如何将UIImage序列化为JSON?
我在用
imageData = UIImagePNGRepresentation(imgvw.image);
并张贴
[dic setObject:imagedata forKey:@"image"];
后
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&theError];
现在的应用程序崩溃终止应用程序由于未捕获的exception' NSInvalidArgumentException
',原因:'JSON写入中的无效types(NSConcreteMutableData)
您需要将您的UIImage转换为NSData,然后将该NSData转换为NSString,这将是您的数据的base64string表示forms。
一旦你从NSData获得了NSString *,你可以把它添加到你的字典中的key @“image”
要将NSData转换为base64types的NSString *,请参阅以下链接: 如何在iphone-sdk上执行base64编码?
在一个更伪的过程将是这样的
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"); }
尝试这个
NSData *imageData = [UIImageJPEGRepresentation(self.photoImageView.image, compression) dataUsingEncoding:NSUTF8StringEncoding];
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];
你可以转换你的形象在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;