2

I want to convert array of Image Paths which are in document directory into Encoded baSE 64 string.

Here is my code

NSArray *recipeImages = [savedImagePath valueForKey:@"Image"];

this array contains path of the images (MULTIPLE IMAGES).

This is how array looks in Logs.

 Saved Images == (
"/Users/ZAL02M/Library/Developer/CoreSimulator/Devices/F1F3C01E-8686-4367-82FB-80B003E2F416/data/Containers/Data/Application/694494B1-0DCA-497A-B8B0-586276EEF240/Documents/cached0.png",
"/Users/ZAL02M/Library/Developer/CoreSimulator/Devices/F1F3C01E-8686-4367-82FB-80B003E2F416/data/Containers/Data/Application/694494B1-0DCA-497A-B8B0-586276EEF240/Documents/cached1.png"
 )

How to make base64 string ???

ios
  • 955
  • 1
  • 12
  • 35

3 Answers3

1

Convert your ImagePaths (Strings) to NSData and from NSData back to string via base64EncodedStringWithOptions:

Here the code:

NSArray *recipeImages = [savedImagePath valueForKey:@"Image"];
NSMutableArray *mutableBase64StringsArray = @[].mutableCopy;

for (NSString *imagePath in recipeImages)
{
    NSData *imagePathData = [imagePath dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64ImagePath = [imagePathData base64EncodedStringWithOptions:0];
    [mutableBase64StringsArray addObject:base64ImagePath];
}

In the mutableBase64StringsArray you have all imagePaths as base64 encoded strings.

Look at this post from SO for more explanations: Base64 Decoding in iOS 7+

Community
  • 1
  • 1
Fabio Berger
  • 1,921
  • 2
  • 24
  • 29
  • Can you give an example , As i have searched alot and not able to figure out what exactly need to do ? – ios Aug 24 '15 at 06:16
1

you can try this

Encoding :

- (NSString *)encodeToBase64String:(UIImage *)image {
 return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

Decoding :

- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
  NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
  return [UIImage imageWithData:data];
}

To get image from your path you can use this code

NSString* imagePath = [recipeImages objectAtIndex:i];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:imagePath];

Then add encoded content to your array.

Hope it helps.

Pradumna Patil
  • 2,180
  • 3
  • 17
  • 46
1

Try this to cycle all your images and save each encoded string into a new array:

NSMutableArray *encodedImages = [NSMutableArray new];

for (NSString *path in recipeImages)
{
    UIImage *image       = [UIImage imageWithContentsOfFile:path];
    NSData *imageData    = UIImagePNGRepresentation(image);
    NSString *dataString = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    [encodedImages addObject:dataString];
}
Jacopo Penzo
  • 2,168
  • 2
  • 24
  • 29