话不多说,以下是实例代码:
文件名:draw.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # author Roc.Wong # 运行方式 python draw.py --width 60 --height 30 test.jpeg from PIL import Image import argparse parser = argparse.ArgumentParser() parser.add_argument('file') parser.add_argument('-o','--output') parser.add_argument('--width', type=int, default=80) parser.add_argument('--height',type=int, default=80) args = parser.parse_args() image = args.file output = args.output width = args.width height = args.height chs = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~i!lI;:,\"^`'. " ascii_char = list(chs) def get_char(r, g, b, alpha=256): if alpha == 0: return ' ' length = len(ascii_char) gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) unit = (257)/length return ascii_char[int(gray/unit)] if __name__ == '__main__': im = Image.open(image) im = im.resize((width, height), Image.NEAREST) txt = '' for i in range(height): for j in range(width): txt += get_char(*im.getpixel((j, i))) txt += '\n' print(txt) # 字符画输出到文件 if output: with open(output, 'w') as f: f.write(txt) else: with open("output.txt", 'w') as f: f.write(txt) 运行方式:找一张图片,运行执行命令 python draw.py --width 60 --height 30 test.jpeg * txt文件打开修改字号小一点
效果展示:
热门文章