[英]How to iterate over all image files in a directory?
我的應用程序使用 iTunes 文件共享。 用戶可以將文件添加到 Documents 目錄。
我必須閱讀這些文件,但要確保它們只是圖像而不是文本文件或其他“垃圾”。
如何遍歷目錄中的文件並僅識別那些是圖像的文件?
我認為我必須以某種方式這樣做:
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];
}
}
但由於某些原因,這很糟糕。 我需要一個 HUUUUUGE if 子句來捕獲所有可能的圖像文件類型,並且有幾十個。
有沒有更智能的方法來真正收集所有圖像文件,無論是.png、.bmp、.jpg、.jpeg、.jpeg2000、.tiff、.raw、.etc?
我稍微記得有一些文件屬性可以告訴文件的一般類型。 我相信有一些抽象的圖像鍵。 但也許有更好的方法?
是的,您可以,只需使用Uniform Type Identifiers 。 這里是:
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);
即使文件名暗示一個圖像文件,它也不一定是圖像。 您可以嘗試從數據中實例化UIImage
並在失敗時拒絕該文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.