简体   繁体   中英

Base64Encoding of UIImage Doesn't Match

I have a UIImage and I want to encode it using base 64. I then send the string to our server.

Our server decodes it using btoa() . It can't do so properly.

After debugging, we found out that the result of encoding/decoding using btoa()/atob() does not match NSData's base64EncodedStringWithOptions when I convert from UIImage to NSData and then encode.

What's weird is they do match when I read the UIImage directly as NSData using dataWithContentsOfFile: instead of converting from UIImage to NSData using UIImagePNGRepresentation()

My problem is that I'm supposed to use an imagepicker that returns a UIImage . I don't want to write the image to file and then read it directly as NSData . it's not efficient. Is there a way to solve this?

Try this for base64 encoding:

+ (NSString*)base64forData:(NSData*)theData
{
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];

    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;

    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;

            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }

        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }

    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM