支持获取常见的图片类型和文件类型
+ (NSString *)getFileTypeWithPath:(NSString *)filePath{
NSUInteger headerLength = 16; // 头文件长度,根据文件类型确定
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
if (fileHandle != nil) {
NSData *headerData = [fileHandle readDataOfLength:headerLength]; // 获取文件头数据
// 将文件头数据转换为十六进制字符串
NSString *hexString = [headerData description];
hexString = [hexString stringByReplacingOccurrencesOfString:@" " withString:@""];
hexString = [hexString stringByReplacingOccurrencesOfString:@"<" withString:@""];
hexString = [hexString stringByReplacingOccurrencesOfString:@">" withString:@""];
hexString = [hexString lowercaseString];
[fileHandle closeFile];
if ([hexString containsString:@"41564920"]) { // 41 56 49 20 avi
return @".avi";
}else if([hexString containsString:@"6d703432"]){ // 6D 70 34 32 mp4
return @".mp4";
}else if ([hexString containsString:@"1a45dfa3"]){ // 1A 45 DF A3 mkv
return @".mkv";
}else if ([hexString containsString:@"6d6f6f76"]){ // 6D 6F 6F 76 mov
return @".mov";
}else if ([hexString containsString:@"464c56"]){ // 46 4C 56 flv
return @".flv";
}else if ([hexString containsString:@"0ad7a300"]){ //文件头标识:0A D7 A3 00 文件类型:ASF(30 26 B2 75 8E 66 CF 11 A6 D9 00 AA 00 62 CE 6C)
return @".wmv";
}else if ([hexString containsString:@"89504e470d0a1a0a"]) { // 89 50 4E 47 0D 0A 1A 0A 8个字节的头文件
return @".png";
}else if([hexString containsString:@"ffd8"]){ // FF D8 jpg/jpeg
return @".jpg";
}else if ([hexString containsString:@"474946"]){ // 47 49 46 gif
return @".gif";
}else if ([hexString containsString:@"424d"]){ // 47 49 46 38 gif
return @".bmp";
}else if ([hexString containsString:@"4949"]||[hexString containsString:@"4d4d"]){ // 49 49 或 4D 4D
return @".tiff";
}else if ([hexString containsString:@"57454250"]){ // 52 49 46 46 XX XX XX XX 57 45 42 50 YY YY YY YY ZZ ZZ ZZ ZZ
return @".webp";
}else if ([hexString containsString:@"00000100"]){ // 00 00 01 00
return @".ico";
}else if ([hexString containsString:@"68656963"]){ // 68 65 69 63
return @".HEIC";
}
} else {
NSLog(@"无法打开文件");
return nil;
}
return nil;
}