Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over all image files in a directory?

My app uses iTunes File Sharing. The user can add files to the Documents directory.

I must read these files but make sure they're only images and not text files or other "garbage".

How can I iterate over the files in a directory and recognize only those which are images?

I assume that I would have to do it somehow like this:

NSMutableArray *retval = [NSMutableArray array];

NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirPath error:&error];
if (files == nil) {
    // error...
}

for (NSString *file in files) {
    if ([file.pathExtension compare:@"png" options:NSCaseInsensitiveSearch] == NSOrderedSame) {        
        NSString *fullPath = [documentsDirPath stringByAppendingPathComponent:file];
        [retval addObject:fullPath];
    }
}

But this is bad for some reasons. I would need a HUUUUUGE if-clause to catch all possible image file types, and there are DOZENS of them.

Is there a more intelligent way to really collect all image files, no matter if .png, .bmp, .jpg, .jpeg, .jpeg2000, .tiff, .raw, .etc?

I slightly remember that there were some kind of file attributes that told the general type of file. There was some abstract image key I believe. But maybe there's an even better method?

like image 437
dontWatchMyProfile Avatar asked May 25 '11 18:05

dontWatchMyProfile


People also ask

How do I iterate all images in a directory in Python?

At first, we imported the pathlib module from Path. Then we pass the directory/folder inside Path() function and used it . glob('*. png') function to iterate through all the images present in this folder.

How do I see multiple files in a directory in Python?

Import the OS module in your notebook. Define a path where the text files are located in your system. Create a list of files and iterate over to find if they all are having the correct extension or not. Read the files using the defined function in the module.


2 Answers

Yes you can, just use Uniform Type Identifiers. Here it is:

NSString *file = @"…"; // path to some file
CFStringRef fileExtension = (CFStringRef) [file pathExtension];
CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);

if (UTTypeConformsTo(fileUTI, kUTTypeImage)) NSLog(@"This is an image");

CFRelease(fileUTI);
like image 135
Cyprian Avatar answered Sep 29 '22 08:09

Cyprian


Even if the filename suggests an image file, it doesn't neccessarily have to be an image. You could try to instanciate a UIImage from the data and reject the file if it fails.

like image 35
Felix Avatar answered Sep 29 '22 10:09

Felix