from struct import *
ch = ['.', ':', '!', '~', '+','=', '^', '*','$', '#']//可以在这里面由浅到深添加字符
ch.reverse()
def calc(R, G, B):#模式L
return R * 299 // 1000 + G * 587 // 1000 + B * 144 / 1000
def character( val):
num = val / 260 * len(ch)
num = round(num)
if num>=len(ch):
num=len(ch)-1
return ch[num]
class rmb:
def __init__(self, path):
file = open(path, 'rb')
self.bfType = file.read(2)
self.bfSize = file.read(4)
self.bfReserved1 = file.read(2)
self.bfReserved2 = file.read(2)
self.bfOffBits = file.read(4)
self.biSize = file.read(4)
self.biWidth = file.read(4)
self.biHeight = file.read(4)
self.biPlanes = file.read(2)
self.biBitCount = file.read(2)
self.biCompression = file.read(4)
self.biSizeImage = file.read(4)
self.biXPelsPerMeter = file.read(4)
self.biYPelsPerMeter = file.read(4)
self.biClrUsed = file.read(4)
self.biClrImportant = file.read(4)
self.bmp_data = []
self.h, = unpack("<i", self.biHeight)
self.w, = unpack("<i", self.biWidth)
print(self.h)
print(self.w)
for height in range(self.h):
bmp_data_row = []
count = 0
for width in range(self.w):
bmp_data_row.append(
[unpack("<B", file.read(1))[0], unpack("<B", file.read(1))[0], unpack("<B", file.read(1))[0]])
count += 3
while count % 4 != 0:
file.read(1)
count += 1
self.bmp_data.append(bmp_data_row)
self.bmp_data.reverse()
file.close()
def write_(self):
res_file = open('res.txt', 'w')
for height in range(self.h):
bmp_data_row = self.bmp_data[height]
for width in range(self.w):
R = bmp_data_row[width][0]
G = bmp_data_row[width][1]
B = bmp_data_row[width][2]
res_file.write(character(calc(R,G,B)))
res_file.write('\n')
res = rmb('1.bmp')#图片路径bmp格式
res.write_()