Tirupati Balan
Tirupati Balan

Reputation: 674

Base64Encoded string in ios not decoding properly on server side using php

I am converting image to NSdata using UIImageJPEGRepresentation(image, 1.0) and then encoding it to base64 using base64 helper class

NSString *imageOne = [self encodeBase64WithData:[imageDict objectForKey:@"ImageOne"]];

and finally sending it to server using post method as json parameter and in server side using php method to decode it.

/* encode & write data (binary) */ 
$ifp = fopen($imageNameWithPath, "wb" ); 
fwrite($ifp, base64_decode($base64ImageString)); 
fclose($ifp); 

After decoding it, I am saving the file as jpeg image and the file is created with proper size and extension but problem is that when I open it, I get the DIMENSION OF IMAGE as 0X0 ..(problem is here)

Server side script is correct as our android developer is also sending base64string and the image is saved as jpeg with proper size and dimension.

This problem is only from iphone side when sending to server for decoding. I have decoded the image using my base64 helper class and it works fine on my iPhone device.

UIImageView *viewImage = [[UIImageView alloc] initWithImage:[UIImage imageWithData: [self decodeBase64WithString:[registerDataDict objectForKey:@"imageOne"]]]];          
[self.view addSubview:viewImage];

Is the process followed by me correct on the device or do I need to change something? Help would be appreciated.

Upvotes: 0

Views: 1955

Answers (2)

Jano
Jano

Reputation: 63697

I'm successfully using this with several OAuth providers: Base64Transcoder.c It's a C class, you can easily turn it into a Objective-C class if you like.

I'm encoding like this:

char base64Result[32];
size_t theResultLength = 32;
[Base64Transcoder base64EncodeData:digest digestLength:CC_SHA1_DIGEST_LENGTH base64Result:base64Result resultLength:&theResultLength];
NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength];

NSString *base64EncodedResult = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

Hmm well, I turned the C function base64EncodeData of the original class into an Objective-C method but you get the idea.

Upvotes: 0

Joe Flynn
Joe Flynn

Reputation: 7204

There are variants on the extra chars used to get to the 65 needed for base64 encoding (26 uppercase + 26 lowercase + 10 digits = 62), and different encoders may use a different subset. PHP is expecting them to be ['+', '/', '='], your application may be using something like ['-', '_', '='].

Once you figure out what the mapping is you can use str_replace before the decode in php. See the wikipedia page on base64 or the php documentation for base64_decode for more info.

Upvotes: 2

Related Questions