当前位置: 首页 > article >正文

python图片转字符画应用

这段代码实现了一个简单的GUI应用程序,允许用户上传一张图片并将其转换为ASCII艺术。具体来说,程序的功能包括:

  1. 图像选择:通过文件对话框让用户选择要转换的图片。
  2. 图像处理
    • 调整图像大小以适应字符画的宽度和高度比例。
    • 将图像转换为灰度图像。
    • 根据像素值将灰度图像映射到一组预定义的ASCII字符上。
  3. 结果显示:在文本区域中显示生成的ASCII艺术。

使用的具体技术包括:

  • Tkinter:用于创建图形用户界面(GUI),提供了按钮、文本区域等组件。
  • Pillow (PIL):用于图像处理操作,如打开、调整大小和转换颜色模式。
  • Python内置异常处理机制:捕获和处理可能发生的错误,并向用户显示友好的错误信息。

以下是完整的代码封装为artifact输出:

import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image
import io

# 定义字符集,从暗到亮排列
ascii_chars = "@%#*+=-:. "

def resize_image(image, new_width=100):
    width, height = image.size
    ratio = height / width / 1.65  # 调整比例以适应字符的高度
    new_height = int(new_width * ratio)
    resized_image = image.resize((new_width, new_height))
    return resized_image

def grayify(image):
    grayscale_image = image.convert("L")
    return grayscale_image

def pixels_to_ascii(image):
    pixels = image.getdata()
    ascii_str = "".join([ascii_chars[pixel // 32] for pixel in pixels])
    img_width = image.width
    ascii_str_len = len(ascii_str)
    ascii_img = "\n".join(
        [
            ascii_str[index : (index + img_width)]
            for index in range(0, ascii_str_len, img_width)
        ]
    )
    return ascii_img.strip()  # 去除首尾空行

def convert_image_to_ascii():
    file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg *.jpeg *.png *.bmp *.gif")])
    if not file_path:
        return
    
    try:
        with open(file_path, "rb") as image_file:
            img = Image.open(io.BytesIO(image_file.read()))
        
        img = resize_image(img)
        img = grayify(img)
        ascii_str = pixels_to_ascii(img)
        
        text_area.delete(1.0, tk.END)
        text_area.insert(tk.END, ascii_str)
    
    except Exception as e:
        messagebox.showerror("Error", f"无法处理图片: {e}")

# 创建主窗口
root = tk.Tk()
root.title("图片转字符画")

# 设置窗口大小
root.geometry("800x600")

# 创建按钮
upload_button = tk.Button(root, text="上传图片并转换", command=convert_image_to_ascii)
upload_button.pack(pady=20)

# 创建文本区域显示ASCII艺术
text_area = tk.Text(root, wrap=tk.WORD, font=("Courier New", 10), bg="black", fg="white")
text_area.pack(expand=True, fill=tk.BOTH, padx=20, pady=20)

# 运行主循环
root.mainloop()




效果图

在这里插入图片描述


http://www.kler.cn/a/536151.html

相关文章:

  • 退格法记单词(类似甘特图)
  • 【银河麒麟高级服务器操作系统】系统日志Call trace现象分析及处理全流程
  • 深浅拷贝~
  • 快速对QWen2.5大模型进行微调
  • js-对象-JSON
  • 免费windows pdf编辑工具
  • Java 集合中的 `removeIf` 和 Stream API 的 `filter`
  • 4.Python字符串和列表:字符串输入、字符串输出、下标和切片、字符串常见函数、列表(list)、列表的循环遍历、列表的增删改查、列表的嵌套、列表的切片
  • 基于单片机的电子抢答器设计(论文+源码+实物)
  • Vue 3 30天精进之旅:Day 17 - 样式和动画
  • UE学习日志#24 C++笔记#10 内存管理1
  • linux——网络计算机{序列化及反序列化(JSON)(ifdef的用法)}
  • DeepSeek本地化部署
  • 【实战】excel分页写入导出大文件
  • 如何在Android Studio中开发一个简单的Android应用?
  • 【截图】selenium自动通过浏览器截取指定元素div的图片
  • 深度剖析 Redis:缓存穿透、击穿与雪崩问题及实战解决方案
  • java将list转成树结构
  • 劳务报酬所得税
  • DeepSeek辅助段落扩写的能力怎么样?
  • 【C++】C++11
  • RAID独立硬盘冗余阵列
  • 11.PPT:世界动物日【25】
  • 【vLLM 学习】使用 CPU 安装
  • leetcode_78子集
  • HTML5 新特性有哪些?