Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get extension from base64 using c#

Tags:

image

base64

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.

like image 970
Anand Gaikwad Avatar asked Jan 07 '23 16:01

Anand Gaikwad


1 Answers

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.

like image 63
piet.t Avatar answered Feb 15 '23 02:02

piet.t