Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize UIImage to JSON?

I am using

imageData = UIImagePNGRepresentation(imgvw.image);

and while posting

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

after

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

now app is crashing Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteMutableData)

like image 314
user2181966 Avatar asked Aug 19 '13 05:08

user2181966


2 Answers

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.

Once you get the NSString* from NSData*, you can add it to your dictionary at key @"image"

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");
    }
like image 183
CodenameLambda1 Avatar answered Sep 20 '22 11:09

CodenameLambda1


Try this

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];
like image 28
Adarsh V C Avatar answered Sep 17 '22 11:09

Adarsh V C