左側效果圖:
實作思路:
通過python的PIL庫,将彩色轉黑白(256種灰階),建立字元集,建立字元集與灰階的映射
動圖
把照片裁成1:1的比例,保證顯示比例正常,通過定時重新整理,模拟一個動感影集
源碼
from PIL import Image
import os
import time
codeLib = '''@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. '''#生成字元畫所需的字元集
count = len(codeLib)
def transform_image(image_file):
#轉換為黑白圖檔,參數"L"表示黑白模式
image_file = image_file.convert("L")
codePic = ''
#size屬性表示圖檔的分辨率,'0'為橫向大小,'1'為縱向
for h in range(0,image_file.size[1]):
for w in range(0,image_file.size[0]):
#傳回指定位置的像素,如果所打開的圖像是多層次的圖檔,那這個方法就傳回一個元組
gray = image_file.getpixel((w,h))
#建立灰階與字元集的映射
codePic = codePic + codeLib[int(((count-1)*gray)/256)]
codePic = codePic+'\r\n'
return codePic
def main():
# 擷取終端的高度
height = os.get_terminal_size().lines
# 擷取同級目錄檔案夾下所有圖檔的清單
the_names = os.listdir("./images")
# 開啟循環
while 1 :
# 周遊每張圖檔
for the_name in the_names:
try:
# 清螢幕
print("\n"*height)
# 拼合目前圖檔名
my_img = open("./images/"+the_name,'rb')
# 打開目前圖檔
image_file = Image.open(my_img)
#調整圖檔尺寸到原來的四分之一
# image_file=image_file.resize((int(image_file.size[0]*0.5), int(image_file.size[1]*0.5)))
image_file=image_file.resize((250, 250))
#列印圖檔
print(transform_image(image_file))
# 每張圖檔停頓5秒
time.sleep(5)
except Exception as e:
pass
if __name__ == "__main__":
main()
文章涉及到的資源我會通過百度網盤分享,為便于管理,資源整合到一張獨立的文章,連結如下: http://www.jianshu.com/p/4f28e1ae08b1