I convert an image to NSData and NSData to base64string using
NSData *imagedata = UIImageJPEGRepresentation(imageView.image, 0.1f);
NSString *c = [NSString base64StringFromData:imagedata];
the fn for stringconversion
+ (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];
}
but the resulted base64string is too long, its length is above 300000.
ie,
int len = c.length;
value of len is above 300000.
the image is of 3 to 4 mb
infact I compress the image to 0.1f
NSData *imagedata = UIImageJPEGRepresentation(iivv.image, 0.1f);
how to minimize the length, is there any other code for base64conversion from NSData?
Base64 will always have larger space requirements than the original data, because it does not use all the bits in one byte. This is done intentionally in order to make sure that higher bits do not cause problems when being handed from one system to another. So in effect it trades space for transmission safety.
It is called Base64 because it only uses 6 bits (2^6=64) for each byte, therefore effectively taking up 5 bytes where the original data only had 4. Or put another way: size will increase by 25%.
The Base64 encoder of course does not care about what the bytes you feed into it represent, so you are free to compress the heck out of your data, as long as it is still in its own format (e. g. create a PNG or JPG out of uncompressed image data) and then encode that as Base64.