Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReConvert bytes to a file Python

For a personal project i would like to convert files of any types (pdf, png, mp3…) to bytes type and then reconvert the bytes file to the original type.
I made the first part, but i need help for the second part.

In the following example, I read a .jpg file as bytes and i save its content in the "content" object. Now i would like to reconvert "content" (bytes type) to the original .jpg type.

test_file = open("cadenas.jpg", "rb")
content = test_file.read()
content

b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x0 ...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could you help me ?

Regards

>Solution :

Pictures uses Base64 encoding.
This should do the job.

import base64

test_file = open('cadenas.jpg', 'rb')
content = test_file.read()

content_encode = base64.encodestring(content)
content_decode = base64.decodebytes(content_encode) 

result_file = open('cadenas2.jpg', 'wb')
result_file.write(content_decode)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading