Skip to content

Instantly share code, notes, and snippets.

@limboinf
Created July 2, 2015 02:57
Show Gist options
  • Save limboinf/33e7e8f3a7707c79d80f to your computer and use it in GitHub Desktop.
Save limboinf/33e7e8f3a7707c79d80f to your computer and use it in GitHub Desktop.
图片>>base64>>二进制文本 转换
#coding=utf-8
__author__ = 'beginman'
__describe__ = '图片>>base64>>二进制文本 转换'
import binascii
import re
def pic2bin(data):
b64 = binascii.b2a_base64(data)
j = 0
f = open('data.txt', 'w')
for i in b64:
# hex to int to bin then padding '0' for 8 digit
bins = bin(int(binascii.b2a_hex(i), 16))[2:].rjust(8, '0')
handle_bins = "".join([bins, " "])
f.write(handle_bins)
j += 1
if j % 6 == 0: # every row with 6 cols, every col with 8 digit
f.write('\n')
f.close()
def bin2pic(data):
result = re.split(r'[ \n]', data) # 按照能够匹配的子串将string分割后返回列表
b64 = ""
for i in result:
if i:
# binary to int to hex then padding '0' for 2 digit
hex_src = str(hex(int(i, 2)))[2:].rjust(2, "0")
# 16进制转ascii码
b64 = "".join([b64, binascii.a2b_hex(hex_src)])
bin_data = binascii.a2b_base64(b64)
f = open("new.png", 'wb')
f.write(bin_data)
f.close()
def main():
f = open("test.png", "rb")
data = f.read()
pic2bin(data)
f.close()
f = open("data.txt")
data = f.read()
bin2pic(data)
f.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment