Finding image type from NSData or UIImage
If you have NSData for the image file, then you can guess at the content type by looking at the first byte:
+ (NSString *)contentTypeForImageData:(NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return @"image/jpeg";
case 0x89:
return @"image/png";
case 0x47:
return @"image/gif";
case 0x49:
case 0x4D:
return @"image/tiff";
}
return nil;
}
How can you read a files MIME-type in objective-c
It's a bit hacky, but it should work, don't know for sure because I'm just guessing at it
There are two options:
- If you just need the MIME type, use the timeoutInterval: NSURLRequest.
- If you want the data as well, you should use the commented out NSURLRequest.
Make sure to perform the request in a thread though, since it's synchronous.
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"imagename" ofType:@"jpg"];
NSString* fullPath = [filePath stringByExpandingTildeInPath];
NSURL* fileUrl = [NSURL fileURLWithPath:fullPath];
//NSURLRequest* fileUrlRequest = [[NSURLRequest alloc] initWithURL:fileUrl];
NSURLRequest* fileUrlRequest = [[NSURLRequest alloc] initWithURL:fileUrl cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:.1];
NSError* error = nil;
NSURLResponse* response = nil;
NSData* fileData = [NSURLConnection sendSynchronousRequest:fileUrlRequest returningResponse:&response error:&error];
fileData; // Ignore this if you're using the timeoutInterval
// request, since the data will be truncated.
NSString* mimeType = [response MIMEType];
[fileUrlRequest release];
How to determine appropriate file extension from MIME Type in Objective-C
Credit goes to @makadev for this link which he posted as a comment, but I thought I would add it as an actual answer. Here's some code derived from that article, which worked on iOS 11. Note that you'll need to link with / import the MobileCoreServices framework. The value you fill in for the mimetype
token below should be an NSString*
.
NSString* uti = (__bridge_transfer NSString*)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef)<#mimetype#>, NULL);
NSString* extension = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)uti, kUTTagClassFilenameExtension);
Path extension and MIME type of file in swift
Assuming you are receiving your data as NSData, follow this Post: https://stackoverflow.com/a/5042365/2798777
In Swift for example:
var c = [UInt32](count: 1, repeatedValue: 0)
(data as! NSData).getBytes(&c, length: 1)
switch (c[0]) {
case 0xFF, 0x89, 0x00:
println("image")
case 0x47:
println("gif")
default:
println("unknown: \(c[0])")
}
Finding video type from NSData
You should check the content type returned by the server:
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)theResponse
{
NSString* content_type = [[(NSHTTPURLResponse*)theResponse allHeaderFields] valueForKey:@"Content-Type"];
//content_type might be image/jpeg, video/mp4 etc.
}
Convert NSData into Default MIME type
NSData
is just raw data.
So you have two primary options:
- 1) transfer the type
- or 2) work with a small set of types you recognize, and programmatically determine the type based on the file formats you receive as input. For example, a pdf's first 4 bytes may be
%PDF
.
If you are working with a small set of formats, you could likely determine the type of data based on the contents of the data. So you might see some APIs which are able to figure out the type the data represents when it has a handful of supported formats which it can identify… but to determine any data would take a long time to process, and to implement. It would also have a fairly high failure rate, due to all the data types/formats available -- published and unpublished, and data formats which don't necessarily have data sequences which identify them uniquely.
Related Topics
How to Integrate Nsurlconnection with Uiprogressview
Changing the Status Bar Text Color in Splash Screen iOS 7
How to Hide/Show Tabbar When Tapped Using Swift in iOS8
Ios7 Safari: Saving to Home-Screen and Persist Token
How to Access Swift 4 Class from Objective-C: "Property Not Found on Object of Type"
Making Video from Uiimage Array with Different Transition Animations
How to Pause and Resume Uiview.Animatewithduration
Proportional Height (Or Width) in Swiftui
Error: Uiview's Window Is Not Equal to Another View's Window
Fbsopenapplicationerrordomain Code =4 Error
Left-Align Image and Center Text on Uibutton
Our App Crashed in iOS 9 Which Upload by Xcode 10
View at the Bottom in a Uiscrollview, with Autolayout
Tableview Reloaddata VS. Beginupdates & Endupdates
Set Background Color of Active Tab Bar Item in Swift
iPhone Collecting Coremotion Data in the Background. (Longer Than 10 Mins)