甚麼是ASCII art
- 文字圖、字元畫、文字畫
- 1982年出現
例子
- 顏文字
: )
== - 複雜一點的
______
/\ \
/ \ \
/ \_____\
_\ / ____/_
/\ \ / /\ \
/ \ \/_/ \ \
/ \__/ \_____\
_\ / \ / ____/_
/\ \ / \ / /\ \
/ \ \/_____/\/_/ \ \
/ \_____\ / \_____\
_\ / / \ / ____/_
/\ \ / / \ / /\ \
/ \ \/_____/ \/_/ \ \
/ \_____\ / \_____\
_\ / / \ / ____/_
/\ \ / / \ / /\ \
/ \ \/_____/ \/_/ \ \
/ \_____\ / \_____\
_\ / /_ ______ ______ _\____/ ____/_
/\ \ / / \/\ \/\ \/\ \/\ \
/ \ \/_____/ \ \ \ \ \ \ \ \ \
/ \_____\ \_____\ \_____\ \_____\ \_____\ \_____\
\ / / / / / / / / / / / /
\ / / / / / / / / / / / /
\/_____/\/_____/\/_____/\/_____/\/_____/\/_____/
- 動畫

開始
pip install Pillow
- 加入圖像
import PIL.Image
img_flag = True
path = input("輸入圖片路徑 : \n")
try:
img = PIL.Image.open(path)
img_flag = True
except:
print(path, "找不到圖片")
- 調整圖像大小
width, height = img.size
aspect_ratio = height/width
new_width = 100
new_height = aspect_ratio * new_width * 0.5625
img = img.resize((new_width, int(new_height)))
- 把圖像轉為灰階
img = img.convert('L')
- 創建ASCII字符列表
- ASCII是由最暗到最亮的排列,也可以自訂下面的字符。
chars = ["%", "*", "^", "^", "-", "+", "<", "!", ":", ".", " "]
- 轉換成ASCII ART
pixels = img.getdata()
new_pixels = [chars[pixel//25] for pixel in pixels]
new_pixels = ''.join(new_pixels)
new_pixels_count = len(new_pixels)
ascii_image = [new_pixels[index:index + new_width]
for index in range(0, new_pixels_count, new_width)]
ascii_image = "\n".join(ascii_image)
with open("ascii_image.txt", "w") as f:
f.write(ascii_image)
結果
::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::@===========:::^==========%:::::::::::
:::::::::::==============================%::::::::
::::::::::================================::::::::
:::::::::%======%=======%=====%==============:::::
:::::::::======================================:::
::::::%========%.............%=======%==========::
:::::==========%......%%%%%%...%%====%..........%:
::::%=============...%%%%%%%%...........%%%%%%...:
::::==================%%%%%%%==........%%%%%.%.=::
:::@=======================%==========^========:::
:::=======================%==================&%:::
::+================&============%====%========::::
::+========================%=============%%:::::::
:::=======================%============%::::::::::
:::%=================================%::::::::::::
::::&%=============================@&:::::::::::::
::&&&&%======%============@%=====&&&&&&&::::::::::
:&&&&&&&&&&%=================%&&&&&&&&&&&:::::::::
:&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&::::::::
:&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&<:::::::
:&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&:::::::