Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e496ac9

Browse files
Create photo_to_ascii.py
1 parent b6adc71 commit e496ac9

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎Photo To Ascii/photo_to_ascii.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from PIL import Image
2+
3+
# ascii characters used to build the output text
4+
CHARS = [".",".",".","1","1","1","1","1","0","0","0"]
5+
# convert each pixel to grayscale
6+
def grayify(image):
7+
grayscale_image = image.convert("L")
8+
return(grayscale_image)
9+
10+
# convert pixels to a string of ascii characters
11+
def pixels_to_ascii(image):
12+
pixels = image.getdata()
13+
characters = "".join([CHARS[pixel//23] for pixel in pixels])
14+
return(characters)
15+
16+
def photoascii():
17+
18+
# attempt to open image from user-input
19+
path = input("Enter a valid pathname to an image:\n")
20+
try:
21+
image = Image.open(path)
22+
except Exception:
23+
print("Invalid path")
24+
return
25+
26+
#Resizing of image
27+
new_width=100
28+
width, height = image.size
29+
ratio = height/width
30+
new_height = int(new_width * ratio)
31+
resized_image = image.resize((new_width, new_height))
32+
33+
# convert image to ascii
34+
new_image_data = pixels_to_ascii(grayify(resized_image))
35+
36+
pixel_count = len(new_image_data)
37+
ascii_image = "\n".join([new_image_data[index:(index+new_width)] for index in range(0, pixel_count, new_width)])
38+
39+
40+
# save result to "ascii_image.txt"
41+
with open("ascii_image.txt", "w") as f:
42+
f.write(ascii_image)
43+
# run program
44+
if __name__=='__main__':
45+
photoascii()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /