Skip to content Skip to sidebar Skip to footer

How To Decode Base64 File Into Binary In Python?

I'm building a system which handles pdf file data (for which I use the PyPDF2 lib). I now obtain a base64 encoded PDF which I can decode and store correctly using the following: im

Solution 1:

Hence the open's binary mode you have to use 'wb' else it gets saved as "text" basically.

import base64
# base64FileData  <= the base64 file data
fileData = base64.urlsafe_b64decode(base64FileData.encode('UTF-8'))
with open('thefilename.pdf', 'wb') as theFile:
    theFile.write(fileData)

Solution 2:

Example your input data is came from this:

with open(local_image_path, "rb") as imageFile:
    str_image_data = base64.b64encode(imageFile.read())

then to get the binary in variable you can try:

import io
import base64

binary_image_data = io.BytesIO(base64.decodebytes(str_image_data))

Post a Comment for "How To Decode Base64 File Into Binary In Python?"