将文本文件转换成图片

from PIL import Image import math def decode(text): str_len = len(text) width = math.ceil(str_len ** 0.5) height = width #生成一张图片 im = Image.new("RGB", (width, height), 0) x, y = 0, 0 for i in text: # 获得字符对应的数字 index = ord(i) # 通过汉字的数字编码得到表示一个像素rgb颜色的数字,(高位数字,中间位数字,低位数字), 一个像素用三个八进制位表示 rgb = ((index & 0xFF0000) >> 16, (index & 0xFF00) >> 8, (index & 0xFF)) #对每个横纵坐标下的像素填充颜色 im.putpixel((x, y), rgb) if x == width - 1: x = 0 y += 1 else: x += 1 return im if __name__ == "__main__": with open("C:/users/mike1/desktop/22377.txt", "r", encoding = "ANSI") as f: text = f.read() final_image = decode(text) final_image.save("C:/users/mike1/desktop/PictureForText.png")

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgzdgg.html