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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
-
|
|
|
|
|
|
|
|
|
!
-
!
-
!
-
!
-
!
-
|
!
-
!
-
!
-
!
-
!
| from PIL import Image
import numpy as np
def jpeg_to_ascii(image_path, width=100, chars=" .:-=+*#%@"):
"""
Convert a JPEG image to ASCII art.
Args:
image_path (str): Path to the JPEG image
width (int): Desired width of ASCII art in characters
chars (str): String of ASCII characters to use, from darkest to lightest
Returns:
str: ASCII art representation of the image
"""
try:
img = Image.open(image_path).convert('L')
aspect_ratio = img.height / img.width
height = int(width * aspect_ratio * 0.5)
img = img.resize((width, height), Image.Resampling.LANCZOS)
pixels = np.array(img)
pixel_chars = [chars[int(pixel * (len(chars) - 1) / 255)]
for row in pixels
for pixel in row]
ascii_art = '\n'.join([''.join(pixel_chars[i:i + width])
for i in range(0, len(pixel_chars), width)])
return ascii_art
except Exception as e:
return f"Error processing image: {str(e)}"
if __name__ == "__main__":
char_sets = {
'simple': " .:-=+*#%@",
'detailed': " .'`^\",:;Il!i><~+_-?][}{1)(|\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$",
'minimal': " .*#@"
}
try:
image_path = 'image.jpg'
print("Simple ASCII Art:")
print(jpeg_to_ascii(image_path, width=100, chars=char_sets['simple']))
print("\nDetailed ASCII Art:")
print(jpeg_to_ascii(image_path, width=100, chars=char_sets['detailed']))
print("\nMinimal ASCII Art:")
print(jpeg_to_ascii(image_path, width=100, chars=char_sets['minimal']))
except Exception as e:
print(f"Error: {str(e)}")
|