What is the way to get file type from base64 string?
- I need a solution which will work on Windows and Linux(Centos7)
E.G.: This is string ; eHh4eHh4
which is = to a text file with xxxxxx
inside.
If websites can do this, I guess it is possible to do it in python:
https://base64.guru/converter/decode/file
What I have tried:
- using
magic
- using
imghdr
Advertisement
Answer
You could write the base64 content into BytesIO:
JavaScript
x
11
11
1
import base64
2
import magic # https://pypi.org/project/python-magic/
3
import io
4
5
data = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=='
6
7
bytesData = io.BytesIO()
8
bytesData.write(base64.b64decode(data))
9
bytesData.seek(0) # Jump to the beginning of the file-like interface to read all content!
10
print(magic.from_buffer(bytesData.read()))
11
Out:
JavaScript
1
2
1
PNG image data, 1 x 1, 8-bit/color RGBA, non-interlaced
2