Skip to content
Advertisement

Get filetype from BASE64 file

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 enter image description here

What I have tried:

  • using magic
  • using imghdr

Advertisement

Answer

You could write the base64 content into BytesIO:

import base64
import magic  # https://pypi.org/project/python-magic/
import io

data = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=='

bytesData = io.BytesIO()
bytesData.write(base64.b64decode(data))
bytesData.seek(0)  # Jump to the beginning of the file-like interface to read all content!
print(magic.from_buffer(bytesData.read()))

Out:

PNG image data, 1 x 1, 8-bit/color RGBA, non-interlaced
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement