开发者

Get a file type from the contents and NOT from extension [duplicate]

开发者 https://www.devze.com 2023-02-04 14:48 出处:网络
This question already has answers here: Closed 10 years ago. Possib开发者_StackOverflowle Duplicate:
This question already has answers here: Closed 10 years ago.

Possib开发者_StackOverflowle Duplicate:

How can you read a files MIME-type in objective-c

In Cocoa, I am trying to get file type, I.E. JPG, JPEG, or PNG, using

LSCopyKindStringForURL((CFURLRef)URL, (CFStringRef *)&kind);

This helps only when the file extension is valid. However, if I rename a PNG file extension to JPEG, it returns JPEG, because LSCopyKindStringForURL returns file type from extension.

Is there any other method that will return me the exact type from the underlying contents of the file?


There is MagicKit.framework, which is a wrapper around libmagic. (This is what the file command uses). In my tests, its determining of UTIs could maybe use a bit of work, but it's probably a good start.

The majority of Launch Services APIs and the like don't look internally at the file's data, AFAIK. That said, the frameworks that would actually deal with such data (in this case of image data, ImageIO.framework, NSImage, etc.), can usually cope with such discrepancies. (For example, change a PNG file extension to .gif, and Preview.app will still gladly open it.)


CGImageSourceRef source = CGImageSourceCreateWithURL( (CFURLRef) URL, NULL);
NSDictionary* metadata = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source,0,NULL);
0

精彩评论

暂无评论...
验证码 换一张
取 消