Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding image type from NSData or UIImage

I am loading an image from a URL provided by a third-party. There is no file extension (or filename for that matter) on the URL (as it is an obscured URL). I can take the data from this (in the form of NSData) and load it into a UIImage and display it fine.

I want to persist this data to a file. However, I don't know what format the data is in (PNG, JPG, BMP)? I assume it is JPG (since it's an image from the web) but is there a programmatic way of finding out for sure? I've looked around StackOverflow and at the documentation and haven't been able to find anything.

TIA.


Edit: Do I really need the file extension? I'm persisting it to an external storage (Amazon S3) but considering that it will always be used in the context of iOS or a browser (both of whom seem fine in interpreting the data without an extension) perhaps this is a non-issue.

like image 446
pschang Avatar asked Nov 10 '10 17:11

pschang


People also ask

What is the difference between UIImage and UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

How do I find my UIImage path?

Once a UIImage is created, the image data is loaded into memory and no longer connected to the file on disk. As such, the file can be deleted or modified without consequence to the UIImage and there is no way of getting the source path from a UIImage.

How do you declare UIImage in Objective C?

For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]]; My UIImage object is declared in .

How do I copy UIImage?

Deep copying UIImage *newImage = [UIImage imageWithData:UIImagePNGRepresentation(oldImage)]; This will copy the data but will require setting the orientation property before handing it to something like UIImageView for proper display. Another way to deep copy would be to draw into the context and grab the result.


1 Answers

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; } 
like image 74
wl. Avatar answered Oct 06 '22 21:10

wl.