Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A quick function for determining an image's file type by its first couple of bytes
@import MobileCoreServices;
static CFStringRef UTTypeForImageData(NSData *data) {
const unsigned char * bytes = [data bytes];
if (data.length >= 8) {
if (bytes[0] == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4E && bytes[3] == 0x47 && bytes[4] == 0x0D && bytes[5] == 0x0A && bytes[6] == 0x1A && bytes[7] == 0x0A) {
return kUTTypePNG;
}
}
if (data.length >= 4) {
if (bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF && bytes[3] == 0xE0) {
return kUTTypeJPEG;
}
}
if (data.length >= 3) {
if (bytes[0] == 0x47 && bytes[1] == 0x49 && bytes[2] == 0x46) {
return kUTTypeGIF;
} else if (bytes[0] == 0x49 && bytes[1] == 0x49 && bytes[2] == 0x2A) {
return kUTTypeBMP;
}
}
if (data.length >= 2) {
if (bytes[0] == 0x42 && bytes[1] == 0x4D) {
return kUTTypeBMP;
}
}
return nil;
}
@kongtomorrow

This comment has been minimized.

Copy link

@kongtomorrow kongtomorrow commented Mar 27, 2014

static CFStringRef UTTypeForImageData(NSData *data) {
    CFStringRef type = NULL;
    CGImageSourceRef isrc = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    if (isrc) {
        type = CGImageSourceGetType(isrc);
        CFRelease(isrc);
    }
    return type;
}
@mattt

This comment has been minimized.

Copy link
Owner Author

@mattt mattt commented Mar 27, 2014

@kongtomorrow Touché!

For those of you following along at home, be sure to add:

@import ImageIO;
@adrianseeley

This comment has been minimized.

Copy link

@adrianseeley adrianseeley commented Mar 28, 2014

this is handy in js too

@sdsykes

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment