我将图像文件存储在缓存目录中。后来我想从缓存目录中获取所有图像文件列表。我正在使用以下代码来获取所有文件。
[fileManager contentsOfDirectoryAtPath:pathForCacheDirectory error:&error]
如何从中分离图像文件。图像文件可以是任何格式。
提前致谢。
答案 0 :(得分:3)
// 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);
答案 1 :(得分:1)
一种野蛮的方式是将您认为是图像的所有扩展程序枚举。 更好的方法是使用UTI,请检查此Get the type of a file in Cocoa
答案 2 :(得分:1)
您可以使用扩展程序过滤文件。
NSArray *contents = [fileManager contentsOfDirectoryAtPath:pathForCacheDirectory error:&error];
for(NSString *filepath in contents){
if ([[filepath pathExtension] isEqualToString: @"png"]) {
// Your code
}
}
答案 3 :(得分:1)
试试这个,希望这会有所帮助。
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
}
}
答案 4 :(得分:0)
见&检查:
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");