Python用图片生成banner.txt文件
1. 代码
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2025/7/1 17:18
# @Author : ning
# @File : generateBanner.py
# @Software: PyCharm
from PIL import Image
def process():
print(f'Hello, World!')
# 打开图片
image = Image.open(r'logo.png').convert('L') # 将图片转为灰度模式,这里需把'your_image_path.jpg'替换为你实际图片路径
# 设置缩放比例,例如0.2表示将图片缩小为原来的20%,可按需调整
scale = 0.2
new_width = int(image.width * 0.1)
new_height = int(image.height * 0.05)
image = image.resize((new_width, new_height))
width, height = image.size
# 定义用于替换像素的字符集,从亮到暗
ascii_chars = [' ', '.', '-', '=', '+', '*', '#', '%', '@']
result = []
for y in range(height):
line = ""
for x in range(width):
pixel = image.getpixel((x, y))
# 根据像素值映射到字符集
char_index = int(pixel / 256 * len(ascii_chars))
line += ascii_chars[char_index]
result.append(line)
# 将结果写入文件
with open('banner.txt', 'w') as f:
for line in result:
f.write(line + '\n')
if __name__ == '__main__':
process()
2. 感受
还可以吧,对比度强的使用体验还不错,