完整教學

環境設定

1
import PIL.Image

完整程式碼

如果覺得輸出文字圖的比例怪怪的可以在ratio那裡調整呦!(像我是/1.65)

提醒!因為此程式碼是要自己輸入原始圖片位置的,所以要先弄清楚圖片位置要輸入什麼喔!

(因為我是用vscode內終端機去跑的所以我就要輸入完整的圖片位置,例如:/Users/admin/desktop/….等)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import PIL.Image

ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]

def resize_image(image, new_width = 100):
width, height = image.size
ratio = height / width / 1.65
new_height = int(new_width*ratio)
resize_image = image.resize((new_width, new_height))
return(resize_image)

def grayify(image):
grayscale_image = image.convert("L")
return(grayscale_image)

def pixels_to_ascii(image):
pixels = image.getdata()
characters = "".join([ASCII_CHARS[pixel//25] for pixel in pixels])
return(characters)

def main(new_width = 100):
path = input("Enter a valid pathname to an image:\n")
try:
image = PIL.Image.open(path)
except:
print(path, "is not a valid pathname to an image\n")

new_image_data = pixels_to_ascii(grayify(resize_image(image)))

pixel_count = len(new_image_data)
ascii_image = "\n".join(new_image_data[i:(i+new_width)] for i in range(0, pixel_count, new_width))

print(ascii_image)

with open("ascii.txt", "w") as f:
f.write(ascii_image)

main()

成品展示

txt