没用的技能增加啦
直接上源码
# 图片转字符画
from PIL import Image
# 转换后的字符
codelib = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
count = len(codelib)
def transform(image_file) :
codepic = ''
image_file = image_file.convert('L') # 将像素转化为灰度值
for i in range(image_file.width) :
for j in range(image_file.height) :
# 得到每一个像素点
gray = image_file.getpixel((i, j)) # 获取该点的RGB值
# 灰度值范围为0-255
# /256是因为如果灰度值正好为255 结果为70 超过列表索引范围
codepic += codelib[int(gray * count / 256)]
codepic += '\n'
return codepic
if __name__ == '__main__':
path = '2.jpg'
with open(path, 'rb') as f : # with + 表达式 + 返回结果 rb 以二进制形式读取
file = Image.open(f)
file = file.resize((file.width, file.height)) # width 纵向 height 横向
text = transform(file)
with open('string.txt', 'w+') as t : # w+ 可读可写如果文件不存在则创建
t.write(text)