-3

below image After editing the image when i click the share/save button how add images in array. i should be display in tableview and it have save locally.

enter image description here

5
  • You have to store image DATA in array not images. Commented Oct 24, 2016 at 7:49
  • could you explain how to save and retrieve in array i want to display in tableview Commented Oct 24, 2016 at 7:52
  • 1
    You can have an array of images 'var images_array=[UIImage]()' or an array of data 'var data_array=[NSData]()' and retrieve images like this 'let image=UIImage(data: data_array[i])'.
    – Marie Dm
    Commented Oct 24, 2016 at 7:59
  • you want to show those array images to another vc or inside the same vc ?
    – vaibhav
    Commented Oct 24, 2016 at 8:06
  • i want to show another view controller Commented Oct 24, 2016 at 8:27

2 Answers 2

2

You can convert a UIImage to NSData like this:

If PNG image

UIImage *image = [UIImage imageNamed:@"imageName.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];

If JPG image

UIImage *image = [UIImage imageNamed:@"imageName.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

Add imageData to array:

[self.arr addObject:imageData];

Load images from NSData:

UIImage *img = [UIImage imageWithData:[self.arr objectAtIndex:0]];
1

Do not store images into an array or a dictionary, unless you want to create a cache, but caches should evict their contents in a future.
You are working on a mobile device that even if is powerful it doesn't has the same hardware of your Mac.
Memory is a limited resource and should be managed with judgment.
If you want to cache temporary those images for performance reason, you can use NSCache, basically is works like mutable dictionary but it is thread safe.
If you want to save them locally it's fine but just keep the path to them in the the array.

- (NSString*) getDocumentsPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = paths[0]; //Get the document directory
    return documentsPath;
}

- (NSString*) writePNGImage: (UIImage*) image withName: (NSString*) imageName {
    NSString *filePath = [[self getDocumentsPath] stringByAppendingPathComponent:imageName]; // Add file name
    NSData *pngData = UIImagePNGRepresentation(image);
    BOOL saved = [pngData writeToFile:filePath atomically:YES]; //Write the file
    if (saved) {
        return filePath;
    }
    return nil;
}

- (UIImage*) readImageAtPath:(NSString*) path {
    NSData *pngData = [NSData dataWithContentsOfFile:path];
    UIImage *image = [UIImage imageWithData:pngData];
    return image;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.