4

I get base64 string as an input to save it as image. but my problem is i dont know what image format user have uploaded. so please help me if anybody know how to get image format or extension from base64 string.

Anand Gaikwad
  • 151
  • 2
  • 9

1 Answers1

9

Each filetype should have a "magic number" at the start of the file that can be used to identify the type.

Some examples (for more see http://en.wikipedia.org/wiki/List_of_file_signatures):

filetype    magic number(hex)
jpg         FF D8 FF
gif         47 49 46 38
png         89 50 4E 47 0D 0A 1A 0A
bmp         42 4D
tiff(LE)    49 49 2A 00
tiff(BE)    4D 4D 00 2A

Your best bet would be to decode the base64 and check the start of the byte-array for one of the byte-patterns.

You might think of converting the byte-patterns to Base64 and check the starting characters of the Base64-image, but this might get you trouble since Base64-encoding always uses a 3-byte-to-4-chars-encoding, so bytes following the magic number might affect the Base-64-representation in the encoded image-file.

piet.t
  • 11,718
  • 21
  • 43
  • 52
  • Thanks for quick reply but my base64 string is something like "iVBORw0KGgoAAAANSUhEUgAAAIkAAABSCAYAAABg3f............." which is not matching with any combination. – Anand Gaikwad Feb 10 '16 at 09:15
  • 2
    That's why I said decode it and use the bytes. Decoding the start of your Base64-String shows the following bytes (in hex) `89 50 4e 47 0d 0a 1a 0a 20 20 20 0d `, so it is obviously a png-file. – piet.t Feb 10 '16 at 09:55