将 PNG 转换为 Python 中的二进制(基数 2)字符串

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

我基本上想读取一个 png 文件并将其转换为二进制(base 2)并将转换后的 base 2 值存储在一个字符串中。我已经尝试了很多东西,但所有的东西都显示出一些错误

您可以使用两种方法:

  1. 首先尝试读取图片并解码成base64格式:

     import base64
    
     with open("my_image.png", "rb") as f:
         png_encoded = base64.b64encode(f.read())
    

    然后,你将base64字符串编码成base2字符串:

     encoded_b2 = "".join([format(n, '08b') for n in png_encoded])
    
     print(encoded_b2)
    

    不过,您可以将 base2 字符串解码为 png 文件:

     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. 第二步,直接读取字节并将字节作为基数2写入字符串:

     from PIL import Image
     from io import BytesIO
    
    
     out = 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)
    

    您可以将 base2 字符串解码为文件:

     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))