宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

要达到的效果如下图所示

二十行python代码实现图片转字符-风君子博客

或者这样

二十行python代码实现图片转字符-风君子博客
源码如下:

from PIL import Image

ascii_char  =list"/\|)1{}$@B%8&WM#ZO0QLCJUYX*hkbdpqwmoahkbdpqwmzcvunxrjft[]?-_+~<>i!lI;:,\"^`'. ")
imgname = "D:/jzm.png"
output ="D:/a.txt"
width =60
height=35

def get_charr,g,b,alpha= 256):
    length = lenascii_char)
    gray = int0.2126 * r + 0.7152 * g + 0.0722 * b)
    unitcount  = 256.0+1)/length
    return  ascii_char[intgray/unitcount)]

img  = Image.openimgname)
img  = img.resizewidth,height),Image.NEAREST)

txt = ""

for i in rangeheight):
    for j in rangewidth):
      txt += get_char*img.getpixelj,i)))
    txt += '\n'

with openoutput,'w') as f:
    f.writetxt)

使用python的PIL库对图片进行处理,将每个像素映射到70个字符上,再一个个像素输出即可

代码注释:

def get_charr,g,b,alpha= 256):
length = lenascii_char)
gray = int0.2126 * r + 0.7152 * g + 0.0722 * b)
unitcount = 256.0+1)/length
return ascii_char[intgray/unitcount)]

版权声明:本文为博主原创文章,转载请附上博文链接!
将彩色图片的RBG数值转化为灰度值,并根据字符的个数计算出每个字符对应几个灰度值,因为灰度值为0~255但只有70个字符符号,大约每个字符对应三个灰度值

img = img.resizewidth,height),Image.NEAREST)

对图片重新设置大小,第二个参数可以设置图片的质量,有四个选项.NEAREST,BILINEAR,BICUBIC,LANCZOS,默认为第一个,第四个图像质量最高

txt += get_char*img.getpixelj,i)))

img.getpixelj,i)返回的是一个三元组元素,加*是为了将其分为三个变量值
———————

作者:NesCafee
原文:https://blog.csdn.net/dpengwang/article/details/79076188