Base64 in iPhone returning different result than o

2019-09-09 05:52发布

问题:

I'm trying to base64 encode an image for upload on iOS, but the stupid thing doesn't have built in support, so I downloaded two libraries and tried them both out, but I think they are returning the wrong values (unless I understand base64 even less than I think I do). This website returns a long string that starts with this: /9j/4Q+zRXhpZgAASUkqAAgAAAAKAA4BAgAgAAAAhgAAAA8BAgAFAAAApgAAABABAgAKAA When I encrypt using the library I downloaded, it starts with this: iVBORw0KGgoAAAANSUhEUgAAAI0AAABnCAIAAACy41YWAABAAElEQVR4AbzdeaylyXUY9nf3 I am 100% sure the first one is correct, because when I use a test program that was written to test the server, that's the same code that it uploads to the server and the server happily decodes the file and saves the image. Here is the test image.

Basically, what I'm thinking is that I need to get a different library for the iPhone / iPad. Another odd thing I noticed is that for some images, the = will be at the end of the string, and for others it won't be. There are three reasons I can think of for this.

1) the iPhone is running out of memory and doesn't want to tell me so it just uploads what it has.

2) the library is broken

3) I'm confused and don't understand base64

Any suggestions?

EDIT: The iPhone is actually the simulator, so I don't know if it will run out of memory before the computer does. I know the android emulator doesn't, but I'm not sure about the iOS simulator.

回答1:

The iPhone output appears to map to the beginning of a PNG per a standard base64 decode (such as this one). The other option you offer (which I trimmed to '/9j/4Q+zRXhpZgAASUkqAAgAAAAKAA4BAgAgAAAAhgAAAA8BAgAFAAAApgAAABABAgAK' to be a valid base64 length) starts with FFD8, the JPEG SOI marker and then contains the text Exif so I'm willing to say is a JPEG.

Is it possible you've inadvertently encoded different files for comparison?

Oh, quick tip by the way, if it helps you test your work — the iPhone has base 64 decoding built in but not obviously. The trick is to create a data url that's base 64 encoded and ask an NSData to load it. E.g.

NSData *decodedData = [NSData dataWithContentsOfURL:
     [NSURL URLWithString:
         @"data:;base64,/9j/4Q+zRXhpZgAASUkqAAgAAAAKAA4BAgAgAAAAhgAAAA8BAgAFAAAApgAAABABAgAK"]];

Where the data:;base64, is directly followed by your base64 data.


Addendum, three years later: since iOS 7 NSData has directly offered -initWithBase64EncodedString:options: so there's no need to formulate a data URL any more.