I Basically want to read a png file and convert it into binary(base 2) and store the converted base 2 value in a string. I've tried so many things, but all of them are showing some error
I Basically want to read a png file and convert it into binary(base 2) and store the converted base 2 value in a string. I've tried so many things, but all of them are showing some error
You can use two approaches:
At first, try to read the image and decode it into base64 format:
import base64with open("my_image.png", "rb") as f:png_encoded = base64.b64encode(f.read())
Then, you encode base64 string into base2 string:
encoded_b2 = "".join([format(n, '08b') for n in png_encoded])print(encoded_b2)
Although, you may decode base2 string into png file:
decoded_b64 = b"".join([bytes(chr(int(encoded_b2[i:i + 8], 2)), "utf-8") for i in range(0, len(encoded_b2), 8)])with open('my_image_decoded.png', 'wb') as f:f.write(base64.b64decode(decoded_b64))
At second, read bytes directly and write byte as base 2 number into string:
from PIL import Imagefrom io import BytesIOout = BytesIO()with Image.open("my_image.png") as img:img.save(out, format="png")image_in_bytes = out.getvalue()encoded_b2 = "".join([format(n, '08b') for n in image_in_bytes])print(encoded_b2)
And you may decode base2 string into file:
decoded_b2 = [int(encoded_b2[i:i + 8], 2) for i in range(0, len(encoded_b2), 8)]with open('my_image_decoded.png', 'wb') as f:f.write(bytes(decoded_b2))