Rajath Shetty K
Rajath Shetty K

Reputation: 424

Get only image files from directory

I am storing image file in cache directory . Later I want to get all image file list from cache directory. I am using following code to get all files.

[fileManager contentsOfDirectoryAtPath:pathForCacheDirectory error:&error]

How to separate image files from this. Image file can be any format.

Thanks in advance.

Upvotes: 1

Views: 1357

Answers (5)

Vedchi
Vedchi

Reputation: 1210

Try this, hope this will help.

 NSArray * contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:YOURPATH error:NULL];
    NSMutableArray * onlyImages = [[NSMutableArray alloc]init];
    for (NSString * contentPath in contents) {
        NSString * lastPath = [contentPath pathExtension];

        if ([lastPath isEqualToString:@"jpg"] || [lastPath isEqualToString:@"jpeg"] || [lastPath isEqualToString:@"png"] ||  /* any other */ ) {
            [onlyImages addObject:contentPath]; // only images
        }

    }

Upvotes: 1

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

// Store your supported image Extensions
NSArray *extensionList = [NSArray arrayWithObjects:@"jpg", @"jpeg", @"png", @"gif", @"bmp", nil];

// Grab the content Directory
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathForCacheDirectory error:&error];

NSMutableArray *listOfImageFiles = [NSMutableArray arrayWithCapacity:0];

// Check for Images of supported type
for(NSString *filepath in contents){
    if ([extensionList containsObject:[filepath pathExtension]])
    {
        // Found Image File
        [listOfImageFiles addObject:filepath];
    }
}
NSLog(@"Lisf of Image Files : %@",listOfImageFiles);

Upvotes: 3

Hasintha Janka
Hasintha Janka

Reputation: 1639

You can filter file using extensions.

 NSArray *contents = [fileManager contentsOfDirectoryAtPath:pathForCacheDirectory error:&error];
    for(NSString *filepath in contents){
       if ([[filepath pathExtension] isEqualToString: @"png"]) {
            // Your code
        }
    }

Upvotes: 1

MeloS
MeloS

Reputation: 7938

a brutal way is to enum all extensions you consider it to be an image. a better way is using UTI, check this Get the type of a file in Cocoa

Upvotes: 1

Vishal
Vishal

Reputation: 8256

See this & check:

CFStringRef fileExtension = (CFStringRef) [file pathExtension];
CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);

if (UTTypeConformsTo(fileUTI, kUTTypeImage)) NSLog(@"It's an image");
else if (UTTypeConformsTo(fileUTI, kUTTypeMovie)) NSLog(@"It's a movie");
else if (UTTypeConformsTo(fileUTI, kUTTypeText)) NSLog(@"It's text");
else  NSLog(@"It's audio");

Upvotes: 0

Related Questions