这是一个简单的Python程序,用于将图片转换为字符画。这个程序使用了Pillow库来处理图片,并使用ASCII字符来构建字符画。
首先,你需要安装Pillow库。如果你还没有安装,可以使用以下命令:
pip install Pillow
接下来是程序代码:
from PIL import Image
def image_to_ascii(image_path, output_width=100):
ascii_chars = ['@', '#', 'S', '%', '?', '*', '+', ';', ':', ',', '.']
try:
image = Image.open(image_path)
except Exception as e:
print(f"无法打开图片: {e}")
return
width, height = image.size
aspect_ratio = height / width / 2
output_height = int(output_width * aspect_ratio)
image = image.resize((output_width, output_height))
image = image.convert('L')
pixels = image.getdata()
ascii_str = ''
for pixel_value in pixels:
ascii_str += ascii_chars[pixel_value // 25]
img_ascii = [ascii_str[index:(index+output_width)] for index in range(0, len(ascii_str), output_width)]
ascii_image = "\n".join(img_ascii)
print(ascii_image)
with open("ascii_image.txt", "w") as f:
f.write(ascii_image)
if __name__ == '__main__':
path = input("请输入图片路径: ")
image_to_ascii(path)
测试图片:

运行结果:

2264

被折叠的 条评论
为什么被折叠?



