Use Python-PIL library to make character images

1. Experimental principle

Use PIL to read the picture, replace the gray value of each pixel with characters, and then output the character string by line, and open it with WordPad
(a small logo is better)

Gray calculation formula: R * 0.299 + G *0.587 + B * 0.114

Two, write the program

from PIL import Image

#替换字符库
code = " .,/;[]=-)<>+(*&^%$#@!_qwertyuioplkhgfdsazxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"

def process(imgfile,f):
    text = ""
    
    #按行遍历全列
    for y in range(imgfile.size[1]):
        for x in range(imgfile.size[0]):
            g,r,b = imgfile.getpixel((x,y))
            
            #得到像素点的RGB值,换算成灰度值
            gray = r*0.299 + g*0.587 + b*0.114
            text = text + code[int(gray/4)]
            
        text = text + "\n"
    f.write(text)


if __name__ == "__main__":
    with open("em.jpg","rb") as i:
        imgfile = Image.open(i)
        #得到图片尺寸
        x = int(imgfile.size[0])
        y = int(imgfile.size[1])
        #替换、写入
        with open("save.txt","w") as f:
            process(imgfile,f)   

Three, conversion effect

Use WordPad to open, set it to Song Ti , font size is 2
Insert picture description here

Finish

Welcome to communicate in the comment area,
thanks for browsing

Guess you like

Origin blog.csdn.net/Xxy605/article/details/107721168