1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | from PIL import Image, ImageFont, ImageDraw from tkinter import filedialog, Tk
def open_path(): root = Tk() root.withdraw() file_path = (filedialog.askopenfilename(title='选择图片文件', filetypes=[('All Files', '*')])) return file_path
print('请选择图片:') IMG = open_path() # 图片路径 ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
print('正在转换......')
def get_char(r, g, b, alpha=256): # alpha透明度 if alpha == 0: return ' ' length = len(ascii_char) gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) unit = (256.0 + 1) / length return ascii_char[int(gray / unit)]
def save_path(): # 保存图片路径 root = Tk() root.withdraw() file_path = (filedialog.asksaveasfilename(title='保存路径', filetypes=[('All Files', '*')])) return file_path
if __name__ == '__main__': img = Image.open(IMG) WIDTH = int(img.width / 6) HEIGHT = int(img.height / 15) img_txt = Image.new("RGB", (img.width, img.height), (255, 255, 255)) img = img.resize((WIDTH, HEIGHT), Image.NEAREST) txt = "" colors = [] for i in range(HEIGHT): for j in range(WIDTH): pixel = img.getpixel((j, i)) colors.append((pixel[0], pixel[1], pixel[2])) # 记录像素颜色信息 if (len(pixel) == 4): txt += get_char(pixel[0], pixel[1], pixel[2], pixel[3]) else: txt += get_char(pixel[0], pixel[1], pixel[2]) txt += '\n' colors.append((255, 255, 255)) dr = ImageDraw.Draw(img_txt) font = ImageFont.load_default().font x = y = 0 # 获取字体的宽高 font_w, font_h = font.getsize(txt[1]) font_h *= 1.37 # 为每个ascii进行上色 for i in range(len(txt)): if (txt[i] == '\n'): x += font_h y = -font_w dr.text([y, x], txt[i], colors[i]) y += font_w
print('转换成功!') print('请选择保存路径:') save_path = save_path()+'.png' img_txt.save(save_path) print('保存成功') img = Image.open(save_path) img.show()
|