Base64 encoded string wont decode (iOS) - ios

I am base64 encoding some data using the following line:
NSString *theData = [serialized base64EncodedStringWithOptions:kNilOptions];
This works correctly and I then pass this string to my web server which stores it in the database.
Later, I am then retrieving this base64 encoded string back from the web server which also works correctly (I have compared both the original before upload and the after download strings and they are the same).
However, when I try to decode this string using:
NSString *theString = [imageDict objectForKey:#"image"];
NSData *imageData = [[NSData alloc] initWithBase64EncodedString:theString
options:kNilOptions];
it just gives me a null value for imageData.
If I output theString it is the correct base64 encoded string I uploaded.
Any ideas why it won't decode?
Thanks in advance.

I used NSDataAdditions.h < see http://code.ohloh.net/file?fid=28qaXmo6xH1Z4clfmn9_wJqDqNI&cid=xVjpNPxNo_A&s=&fp=308694&mp=&projSelected=true#L0 and for .m http://code.ohloh.net/file?fid=tXQCCVHemN1iAx6ZQSy1VkBACXA&cid=xVjpNPxNo_A&s=&fp=308694&mp&projSelected=true#L0 >
NSData *imageData = [NSData dataWithBase64EncodedString:theString];

Related

Change UIImage Class to send to node.js server in iOS?

I am creating an App for chatting. Now I want to send UIImage to server in JSON String so other user can receive image.I am using socket.io so I have to send event with data(JSON String).
Problems- When I try to convert UIImage to NSData and convert it to JSON it gives error 'Invalid type in JSON write (NSConcreteMutableData)'.
What will be the correct way to send UIImage to server?
code
NSData *imgData = UIImageJPEGRepresentation(image, .2);
NSString * imageString =[[NSString alloc]initWithBytes:[imageData bytes] length:[imageData length] encoding:NSASCIIStringEncoding];
also tried
NSString * imageString =[[NSString alloc]initWithData :imgData encoding:NSUTF8StringEncoding];
converted data to dictionary:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:imgData options:NSJSONReadingAllowFragments error:&error];
Any help would be appreciated.
The general approach would be to base64 encode the image data. In this way the image data is converted to a string format instead of binary.
Since iOS 7 NSData has provided base64 conversion methods that you can use instead of your current attempted conversion to and from strings.

iOS: Convert UIImage to base64 without UIImageRepresentation

I think everything is in the title:
I have a UIImage that I need to convert to base64 without using UIImagePNGRepresentation or UIImageJPEGRepresentation. Objective C is what I code in.
Is this possible?
When converting to base64 string:
NSData *imageBase64Data = [ImageData base64EncodedDataWithOptions:0];
NSString *imageBase64String = [[NSString alloc] initWithData:imageBase64Data encoding: NSUTF8StringEncoding];
And converting it back:
NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:0];
UIImage *image = [UIImage imageWithData:data];
as you can see from the code, we just converted the string back to data(originally image)
Convert the image to NSData without assigning a png or jpg representation like this:
CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
Then convert the data to a base64 string using a library like this one: https://github.com/ekscrypto/Base64

How to convert Base64 encoded NSString into Byte Array(Java) in ios?

I have an Image that is converted into NSData and which in-turn is converted into base64 encoded NSString. Now i have a service that accepts this base64 encoded string in only Byte Array(Java Supported). I tried different options but i am not able to convert the encoded string into Byte Array type. Can someone please help me on how to convert the encoded string into Byte Array(Java supported)?
Below is my answer for this. I came to know that the easiest way is to convert the image data into byte array directly without base64encoding the data.
NSError* error;
NSString* str=[[NSBundle mainBundle] pathForResource:#"black-circle" ofType:#"png"];
NSData* data= [NSData dataWithContentsOfFile:str options:NSDataReadingUncached error:&error];
NSInteger length=[data length];
const char* dataBytes=[data bytes];
Now you can traverse each byte using dataBytes pointer.
Hope this helps.
You can try out :
Use-[NSString UTF8String] which returns const char*.
or this link will help you :
Convert NSString into byte array iphone
We can get the NSdata from the NSStirng and then convert NSData into Byte Array. The easier way is to convert the captured image data into Byte Array using uint8_t. Below is the code snippet that does the trick.
NSData to Byte Array:-
NSData *data = UIImagePNGRepresentation(imageCaptured);
uint8_t byteArray[[data length]];
[data getBytes:&byteArray];
NSMutableString *byteArrayString = [[NSMutableString alloc]init];
for (int i = 0 ; i < sizeof(byteArray); i++) {
[byteArrayString appendString:[NSString stringWithFormat:#"%d,",byteArray[i]]];
}
// Removing last extra comma
[byteArrayString deleteCharactersInRange:NSMakeRange([byteArrayString length]-1, 1)];

Proper way to get the byte array from the JSON

I am trying to get the image from the byte array. I can only get the image if enter the byte array values into the string directly as follows:
NSMutableString *imagen = [[NSMutableString alloc] initWithString:#"-1,-40,-1,-32,0,16,74,70,73,70,0,1,0,1,0,96,0,96,0,0,-1,-2,0,31,76,69,65,68,32,84,101,99,104,110,111,108,111,103,105,101,115,32,73,110,99,46,32,86,49,46,48,49,0,-1,-37,0,-124,0,5,5,5,8,5,8,12,7,7,12,12,9,9,9,12,13,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13];
//this way works fine
IF i try to get the byte array into string as follows,then I couldnt get the image:
NSString *logo=[NSString stringWithFormat:#"%#",[[JSON valueForKey:#"request"]valueForKey:#"logo" ]];
NSMutableString *imagen = [[NSMutableString alloc] initWithString:logo];
//this way doesnt work out
I am following this link to get the thing done.this link
Could you please tell me whats the proper way to get byte array from JSON?
This is not executable code, it is a method to use:
You get the JSON in self.receivedData
Convert it into an object with
NSDictionary *jsonObject = NSJSONSerialization JSONObjectWithData:
** Unknown how the image data is encoded in the JSON. If it is Base64 encoded:
Get the Base64image string with
NSString *imageString = jsonObject[#"request"][#"logo"]
Convert the Base64 string into data:
NSData *imageData = [NSData alloc] initWithBase64EncodedString: imageString options:
Get an image with
UIImage *logoImage = [imageData imageWithData]
All in all you have way to much code that accomplished nothing and converting the image data to an NSString is incorrect.
Converting to a string and then back to data accomplishes nothing.
This code seems confused? The link you posted has string encodings which contain negative numbers. You parse these as signed but then assign them to an array of unsigned uint8_t using bytes[i] = (uint8_t)byte;.
I think you need to post the string encoding format and an example?

Save and load image from SQL database

I'm trying to display an image from my Database.
This part works nicely.
I save the image in the DB like this :
UIImage *resizedImg = [Generics scaleImage:self.photo.image toResolution:self.photo.frame.size.width and:self.photo.frame.size.height];
NSData *imgData = UIImageJPEGRepresentation(resizedImg, 0.9);
NSString *stringDataImage = [NSString stringWithFormat:#"%#",imgData];
[dict setObject:stringDataImage for key#"image"];
// POST Request to save the image in DB ...
Now when I try to load the image and set it into my UIImageView I do this way :
NSData *data = [[[MyUser sharedUser] picture] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];
Or
NSData *data = [[[MyUser sharedUser] picture] dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
self.imageView.image = [UIImage withData:data];
But this doesn't work.
data is not equal to imgData, I think it's the encoding but I can find the good one.
And [UIImage withData:data] return nil;
Can you help me?
EDIT :
Convert and save
UIImage *resizedImg = [Generics scaleImage:self.photo.image toResolution:self.photo.frame.size.width and:self.photo.frame.size.height];
NSData *imgData = UIImageJPEGRepresentation(resizedImg, 0.9);
[dict setObject:[imgData base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength] forKey:#"image"];
Load the image
NSData *data = [[NSData alloc] initWithBase64EncodedData:[[MyUser sharedUser] picture] options:kNilOptions];
NSLog(#"%#", data);
self.image.image = [UIImage imageWithData:data];
You are converting the NSData to a string and saving that to your database. Two issues:
Your choice of using the stringWithFormat construct is an inefficient string representation of your data (resulting in string representation that is roughly twice the size). You probably want to use base64 (for which the string representation is only 33% larger).
You are saving your string representation, but never converting it back to binary format after retrieving it. You could write a routine to do this, but it's better to just use established base64 formats.
If you want to save the image as a string in your database, you should use base64. Historically we would have directed you to one of the many third party libraries (see How do I do base64 encoding on iphone-sdk?) for converting from binary data to base64 string (and back), or, iOS 7 now has native base 64 encoding (and exposes the private iOS 4 method, in case you need to support earlier versions of iOS).
Thus to convert NSData to NSString base64 representation:
NSString *string;
if ([data respondsToSelector:#selector(base64EncodedStringWithOptions:)]) {
string = [data base64EncodedStringWithOptions:kNilOptions]; // iOS 7+
} else {
string = [data base64Encoding]; // pre iOS7
}
And to convert base64 string back to NSData:
NSData *data;
if ([NSData instancesRespondToSelector:#selector(initWithBase64EncodedString:options:)]) {
data = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions]; // iOS 7+
} else {
data = [[NSData alloc] initWithBase64Encoding:string]; // pre iOS7
}
If you really want to turn binary data into a string you should be using base64 encoding. Luckily for you, NSData now supports Base64 natively
So you could get your string from data with:
NSString *stringDataImage = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
And you could turn this back into NSData with:
NSData *imgData = [[NSData alloc] initWithBase64EncodedString:stringDataImage options:kNilOptions];

Resources