【Python】图片转字符画程序

这是一个简单的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)
    

测试图片

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值