1. 程式人生 > 實用技巧 >將文字檔案轉換成圖片

將文字檔案轉換成圖片

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")