Convert PNG to a binary (base 2) string in Python

2024/10/11 10:24:33

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

Answer

You can use two approaches:

  1. 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))
    
  2. 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))
    
https://en.xdnf.cn/q/118338.html

Related Q&A

Turbodbc installation on Windows 10

I tried installing turbodbc and it gives me the following error and not sure whats wrong here.My python version is 3.7My command line output from Windows 10 Pro. C:\Users\marunachalam\Downloads>pip …

how to convert a text into tuples in a list in python

I am a beginner in python and desperately need someones help.I am trying to convert a text into tuples in a list. The original text was already tokenized and each pos was tagged as below:The/DT Fulton/…

Trying to call a function within class but its not working [duplicate]

This question already has answers here:TypeError: attack() missing 1 required positional argument: self(2 answers)Closed 3 years ago.I am trying to call a function but its not working. here is the code…

Tkinter Label not showing Int variable

Im trying to make a simple RPG where as you collect gold it will be showed in a label, but it doesnt!! Here is the code:def start():Inv=Tk()gold = IntVar(value=78)EtkI2=Label(Inv, textvariable=gold).pa…

How to refer a certain place in a line in Python

I have this little piece of code:g = open("spheretop1.stl", "r") m = open("morelinestop1.gcode", "w") searchlines = g.readlines() file = "" for i, line…

List comprehension output is None [duplicate]

This question already has answers here:Python list comprehension: list sub-items without duplicates(6 answers)Closed 8 years ago.Im new to python and I wanted to try to use list comprehension but outco…

error while inserting into mysql from python for loop [duplicate]

This question already has answers here:Closed 12 years ago.Possible Duplicate:convert list to string to insert into my sql in one row in python scrapy Is this script correct. I want to insert the scra…

Half of Matrix Size Missing

I wanted to ask why is it that some of my matrices in Python are missing a size value? The matrices/arrays that re defined show the numbers in them, but the size is missing and it is throwing me other…

Clicking Side Panel Elements in Selenium Without IFrames

I want to download U.S. Department of Housing and Urban Development data using Pythons Selenium. Heres my code. import os from selenium import webdriver from webdriver_manager.chrome import ChromeDrive…

Library to extract data from open Excel workbooks

I am trying to extract data from workbooks that are already open. I have found the xlrd library, but it appears you can only use this with workbooks you open through Python. The workbooks I will use in…