7

我在用

imageData = UIImagePNGRepresentation(imgvw.image);

并在发帖时

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

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

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

4

3 回答 3

11

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

从 NSData* 获得 NSString* 后,您可以将其添加到您的字典中的键 @"image"

要将 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");
    }
于 2013-08-19T05:47:07.350 回答
4

尝试这个

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];
于 2013-08-19T05:31:08.660 回答
-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;
于 2013-08-19T05:24:30.233 回答