字符图-接上次的文章

#字符图
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')

字符画_参考实验楼
字符画

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值