4

Update:

I took the base64 string iOS was generating and decoded it to a binary file through a website. The image was encoded properly it seems.

My problem then is with the rails side of things. I'm displaying the image using the following code but it's just showing a broken image.

<td><%= ('<img src="data:image/jpg;base64,%s">' % Base64.encode64(user.imagestring)).html_safe %></td>

I'm trying to encode a base64 string to send through JSON to my web service (Rails using Postgresql). I've converted a UIImage to NSData and am now converting it to a base64 string.

I'm using the new base64EncodedStringWithOptions method. It converts to a long string but on my web service the image appears broken.

I uploaded the image to an image to base64 converter website and it returns a slightly different string.

Is the problem with the iOS encoder or am I doing something wrong?

UIImage *image = [UIImage imageNamed:@"image.png"];
NSData *imageData = UIImagePNGRepresentation(image);
NSString *blob = [imageData base64EncodedStringWithOptions:0];

2 Answers2

1

You are doing a round-trip through UIImage and UIImagePNGRepresentation(image) to get the data to be base 64 coded. That might not be the same contents as the original file. There are tons of options when coding images, and you're not assured that your roundtrip will use the same options.

I would, instead, suggest just loading the NSData directly:

NSString *path = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
NSData *imageData = [NSData dataWithContentsOfFile:path];

Try running that through your base 64 coding and see what you get.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Thanks for tip. My problem turned out to be the ruby code but your answer could explain the differences in the encoded string. –  Nov 06 '13 at 12:11
0

The problem was with the ruby code. This worked:

<td><%= ('<img src="data:image/png;base64,%s">' % user.image).html_safe %></td>