How to convert UIImage to JSON file in iPhone? - iphone

I have been using NSJSONSerialization class for converting fields of my object to JSON. Sadly only NSString, NSNumber, NSArray, NSDictionary, or NSNull types are supported.
As my object has one additional field, that is UIImage, I am at loss as to how to deal with it. I am sure many people have encountered this common problem, so what is best method to approach this?

You can encode UIImage data by base64, and add it to json object.
To get data from UIImage, you can use UIImagePNGRepresentation and UIImageJPEGRepresentation.
The code like this,
NSData *imageData = UIImagePNGRepresentation(image);
NSString *base64encodedStr = base64encode(imageData);
[dict setObject:base64encodedStr forKey:#"myImage"];
//then covert dict to json object.
To restore UIImage data, just parse json object and decode the data by base64.
Hope this can help you.

You could convert your images 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];

NSString *base64encodedStr = [imageData base64Encoding];

Related

Convert NSMutableData to NSData in Swift

I have a method which is returning NSMutableData. I need to pass this NSMutableData to another method but that method is expecting only NSData. I am trying to find any method/solution to convert NSMutableData to NSdata. But still no luck.
In Objective C, it can be done like this
NSData *immutableData = [NSData dataWithData:mutableData];
I am not sure how it can be done in Swift?Can someone help me in this?
Simply pass the NSMutableData to any method that expects NSData. Since it's a subclass, it will work fine.
But if you really want to do the conversion, simply do (Swift 3):
let data = someNSMutableDataVariable.copy() as! NSData
or
let data = NSData(data: someNSMutableDataVariable as Data)
It may make sense to update your code to use Data instead of NSMutableData or NSData. Just like using String instead of NSString and NSMutableString.

-base64Encoding return type defaults to id

In my application when i try with following coding i get the warning as
Code
[UIImageJPEGRepresentation(petAvadar.image, 1.0)base64Encoding]
WARNING
Instance method '-base64Encoding' not found (return type defaults to 'id')
How to remove this warning,Please help me to solve.
Then convert your UIImage object into NSData the following way:
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
And then apply Base64 encoding to convert it into a base64 encoded string:
NSString *encodedString = [imageData base64Encoding];
once check this one
You need to declare your function in the header file.
You should add a line like this :
-(returnType)base64Encoding;
Where returnType is the type returned by your method, like NSString*, NSInteger, void or whatever your method returns.
Make sure that you have donlaoded Base64 lib classes from here
then import Base64.h use below code snip
For Encoding Image to Base64
NSData* data = UIImageJPEGRepresentation(yourImage, 1.0f);
[Base64 initialize];
NSString *strEncoded = [Base64 encode:data];
and Decode Base64 as image:
[Base64 initialize];
NSData* data = [Base64 decode:strEncoded ];;
image.image = [UIImage imageWithData:data];
Alos you may like to check this and this link as well

NSData/UIImage to String

Is it possible to convert NSData/UIImage Data Representation as JPEG to a String, to be sent over HTTP to a PHP File to save this string in a database, and then retrive it later on in the application and convert it back into an NSData/UIImage Object?
I have tried Base64 Encoding Libraries but base64 doesn't seem valid as the image doesn't display correctly on a HTML Page.
Any suggestions?
Edit.
I was using the following library:
http://www.imthi.com/blog/programming/iphone-sdk-base64-encode-decode.php
And converting in the following way:
NSData *imageData = UIImageJPEGRepresentation(MyImage.image, 90);
[Base64 initialize];
NSData *encoded = [Base64 encode:imageData];
NSLog(#"%#",encoded);
This does chug out alot of BASE64 but when I save it to a file and try to view it, I just get the eror loading image [?] in Chrome.
Thanks
The point of encoding an NSData object to base 64 is so you can represent the data as a string that can be stored or transferred more easily. You then need to decode the base 64 encoded string back into NSData. This data can then be used to create a new UIImage. Your server needs to do this decoding to get back the original data.
Your code has a mistake. This line:
NSData *encoded = [Base64 encode:imageData];
should be:
NSString *encoded = [Base64 encode:imageData];
Notice that you get back a string, not data.
You commented that you wrote the encoded string to a file then couldn't view the image. Of course not. If you want to write the image data to a file so the file is actually viewable as the image, then don't encode the data first. Write the raw image data to a file.
you can convert image to string like this
first convert your UIImage to NSData & then convert that ata into string by using encodeBase64WithData
NSString *imageOne = [self encodeBase64WithData:[imageDict objectForKey:#"ImageOne"]];
and again string to UIImage like this:
[UIImage imageWithData: [self decodeBase64WithString:[registerDataDict objectForKey:#"imageOne"]]];
You need to import Base64.h
You can directly use like this way:
UIImage *image = _btnaddCountryIcon.imageView.image;
NSData *imageData = UIImagePNGRepresentation(image);
NSString *base64 = [Base64 encode:imageData];
directly you can convert to NSString. This code works fine for me.

Get image from service URL in iPhone?

I have to retrieve image from rest service url.But I don't have a separate URL for image(path of the image).I m getting it in a XML file.I did parsing of XML and stored it in an array.Now I couldn't understand how to retrieve image from it ..
My array looks like this:
(
{
Image = "
9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBxdWFsaXR5ID0gODAK/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEB
cUGBgXFBYWGh0lHxobIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgEKwZAAwEiAAIRAQMR
Af/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RV
VldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v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jt1LupuKMUBceDRupuKMUwuSbqN1MxS4oEP3UbqZilwaAH5pc0zFGDQA/dRupmDRzQA/dS7qZzRzQA/dRupnNHNAEm6jdTOaM0ASbqN1R0ZoAk3UbqjzRmgCTdRuqPNGaAJN1G6o80ZoAk3UbqZmkzQBLuo3VFmlzQBJuo3VHmjNAEu6jdUWaM0AS7qN1RZo3UAS7qN1RbqTdQBNuo3VDuozQBNuo3VDmjdQBNuo3VDuo3Uhku6jdUO6jdQBNuo3VDupN1AE26jdUO6jdQBNuo3VDuo3Ug
//big array </Image>
}
)
I couldn't understand what format(byte array or base64?) is this coming from service?
How to retrieve image from this in a tableViewCell?
If this is base64 string then You can decode base64 string to NSData using this and you can access UIImage from NSData.
+ (NSData *)decodeBase64WithString:(NSString *)strBase64;
This format is base64 then you should decode this string into data and get image. Use nsdata+ base64 class and import those class in your project.
Use + (NSData *)decodeBase64WithString:(NSString *)strBase64; method in your code. call like this
NSData *imageData = [NSData decodeBase64WithString:strBase64];
Edit:
NSString *yourBase64String = [yourDictionary valueForKey:#"Image"];
NSData *imageData = [NSData decodeBase64WithString:yourBase64String];
UIImage * image = [UIImage imageWithData:imageData];
May be it is because there were modifications to the NSData+Base64 files but the method now is dataFromBase64String instead of decodeBase64WithString

UIImage from bytes held in NSString

I am trying to create a UIImage from a byte array that is actually held within a NSString.
Can someone please tell me how I can do that?
Here is what I was thinking of doing:
NSString *sourceString = #"mYActualBytesAREinHERe=";
//get the bytes
const char *bytesArray = [sourceString cStringUsingEncoding:NSASCIIStringEncoding];
//build the NSData object
NSData *data = [NSData dataWithBytes:bytesArray length:[sourceString length]];
//create actual image
UIImage *image = [UIImage imageWithData:data];
The problem is image is always 0x0 (nil).
Any suggestions would be appreciated.
Thanks!
To convert an image to string you need a method to convert NSData to a base64Encoded string and back (lots of examples here). The easiest ones to use are categories on NSData so you can do something like this:
UIImage* pic = [UIImage imageNamed:#"sample.png"];
NSData* pictureData = UIImagePNGRepresentation(pic);
NSString* pictureDataString = [pictureData base64Encoding];
To go the other way you need a reverse converter:
UIImage* image = [UIImage imageWithData:[NSData
dataFromBase64EncodedString: pictureDataString]];
[UIImage imageWithData:data]; will return nil if it doesn't understand the data being passed to it. I would double check your encoding, etc. It's odd that a binary string would hold pure image data without some kind of encoding (base64, etc.). String encodings and binary encodings aren't compatible.
I bet your image data has some null characters in there (0x00) and as you know that is the terminator for the string, so when you ask for the C string, you probably get way-way too little data.
Try something like
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding;
to generate your NSData.
If that doesn't work you need to evaluate whether the setting the data into an NSString (with embedded null chars) isn't causing a loss of data too.
Like one of the other respondents, perhaps base-64 encoding your data would be a good idea (if using a string to transport the img data is a requirement)
Good luck.