1

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
Oksana Ok
  • 515
  • 3
  • 7
  • 19
  • How and what did you explicitly try ? – Maurice Meyer Aug 09 '21 at 12:39
  • @MauriceMeyer These ones... `https://stackoverflow.com/questions/21034201/how-to-find-file-extension-of-base64-encoded-image-in-python` , `https://stackoverflow.com/questions/57785500/how-to-know-mime-type-of-a-file-from-base64-encoded-data-in-python` – Oksana Ok Aug 09 '21 at 12:40

1 Answers1

2

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
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47