How to convert UIImage to JSON file in iPhone?

I am using the NSJSONSerialization class to convert the fields of my object to JSON. Unfortunately, only the types NSString, NSNumber, NSArray, NSDictionary, or NSNull are supported .

Since my object has one additional field, it is UIImage , I am losing information on how to deal with this. I'm sure many people have come across this common problem, so what's the best way to get close to this?

+4
source share
3 answers

You can encode UIImage data with base64 and add it to a json object. To get data from UIImage, you can use UIImagePNGRepresentation and UIImageJPEGRepresentation .

Code like this

 NSData *imageData = UIImagePNGRepresentation(image); NSString *base64encodedStr = base64encode(imageData); [dict setObject:base64encodedStr forKey:@"myImage"]; //then covert dict to json object. 

To recover UIImage data, simply UIImage json object and decode the data based on 64.

Hope this helps you.

+2
source

You can convert your image data to a string and then write that string.

 NSData *imageData = UIPNGRepresentation(image); NSString *imageString = [[NSString alloc] initWithData:imageData encoding:NSUTF8StringEncoding]; //I don't know how to use NSJSONSerialization //[NSJSONSerialization serializeString:imageString]; 
+1
source
 NSString *base64encodedStr = [imageData base64Encoding]; 
0
source

All Articles