Rorschach Rorschach - 3 months ago 7x
iOS Question

Extract image type from NSData or encoded image


I have a function where a user can upload and send over an image from my ios to my rails app and it works for

files. I would like to make it work for all image types. All I need to do is send over the image type in the API POST.

So far the user uploads the image and its an NSData, then I encoded into a
and put it into a
and send it over. This works for .jpg's.


How do I get the image's type from the
or the encoded string of an image?


Here is the
of a very small .png that the user might try to upload.

<89504e47 0d0a1a0a 0000000d 49484452 0000000a 0000000a 08060000 008d32cf bd000000 01735247 4200aece 1ce90000 00097048 59730000 16250000 16250149 5224f000 00001c69 444f5400 00000200 00000000 00000500 00002800 00000500 00000500 00005ec1 07ed5500 00002a49 44415428 1562f88f 04181818 fea36398 34038c01 a2d11581 f8308060 11ab109b 691826e2 5284ac10 000000ff ff232a1e 6b000000 27494441 5463f80f 040c0c0c 3831481e 0418c004 0e856015 5002a742 644560c3 c0041613 c9560800 782fe719 4293f838 00000000 49454e44 ae426082>

Here is output of

strBase64:String = image.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)



You should check your Base 64 encoded string for magic numbers in files.

For example for PNG:

PNG image files begin with an 8-byte signature which identifies the file as a PNG file and allows detection of common file transfer problems: \211 P N G \r \n \032 \n (89 50 4E 47 0D 0A 1A 0A).


JPEG image files begin with FF D8 and end with FF D9. JPEG/JFIF files contain the ASCII code for "JFIF" (4A 46 49 46) as a null terminated string. JPEG/Exif files contain the ASCII code for "Exif" (45 78 69 66) also as a null terminated string, followed by more metadata about the file.

So parse your string, detect matching of any magic number, map magic number to image file type.