python动态图片转字符画_【小工具】使用python将图片转彩色字符画

[Python] 纯文本查看 复制代码# -*- coding:utf-8 -*-

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("ABCDE") # 所用字符列表

print('正在转换......')

# 将256灰度映射到70个字符上

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__':

im = Image.open(IMG)

WIDTH = int(im.width / 6) # 高度比例为原图的1/6较好,由于字体宽度

HEIGHT = int(im.height / 15) # 高度比例为原图的1/15较好,由于字体高度

im_txt = Image.new("RGB", (im.width, im.height), (255, 255, 255))

im = im.resize((WIDTH, HEIGHT), Image.NEAREST)

txt = ""

colors = []

for i in range(HEIGHT):

for j in range(WIDTH):

pixel = im.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(im_txt)

font = ImageFont.load_default().font # 获取字体

x = y = 0

# 获取字体的宽高

font_w, font_h = font.getsize(txt[1])

font_h *= 1.37 # 调整后更佳

# ImageDraw为每个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'

im_txt.save(save_path)

print('保存成功')

im = Image.open(save_path)

im.show()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值