#字符图
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
# 将256灰度映射到70个字符上
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 = (256.0 + 1)/length
return ascii_char[int(gray/unit)]
from PIL import Image, ImageDraw, ImageFont
im = Image.open(r'C:\Users\hao\Desktop\编程\趣味案例\微信图片_20181225192451.jpg').convert('RGB')
raw_width = im.width
raw_height = im.height
im_txt = Image.new('RGB', (raw_width, raw_height), (255, 255, 255)) #Image.new(mode,size,color)
dr = ImageDraw.Draw(im_txt)
font = ImageFont.load_default().font
char = ' '
font_w, font_h = font.getsize(char) #获取单个字符的尺寸
width = int(raw_width/font_w)
height = int(raw_height/font_h)
im = im.resize((width, height), Image.NEAREST)
txt = ""
for row in range(height):
for col in range(width):
pixel = im.getpixel((col,row))
txt += get_char(*pixel)
txt += '\n'
x = y = 0 # x对应图中横坐标,y对应纵坐标
for i in range(len(txt)):
if(txt[i] == '\n'):
x = 0
y += font_h
else:
dr.text((x,y), txt[i], font=font, fill=True)
x += font_w
im_txt.save(r'C:\Users\hao\Desktop\编程\趣味案例\**.jpg')
字符图-接上次的文章
猜你喜欢
转载自blog.csdn.net/shuyueliang1/article/details/85407705
今日推荐
周排行