You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PyCharm控制台内直接显示图片 无需弹出独立外部窗口

解决方案

PyCharm 目前有两种可实现控制台内直接显示图片的方案,按需选择即可:

方案1:IPython 内置渲染(显示原图,仅支持PyCharm内置Python Console)

该方案可以直接展示原始图片,不需要转格式,仅需开启PyCharm的IPython支持:

  1. 先确认配置开启:打开 File → Settings → Build, Execution, Deployment → Console → Python Console,勾选 Use IPython if available 选项
  2. 安装依赖:
pip install pillow ipython
  1. 代码示例:
from IPython.display import display
from PIL import Image

print("**请问以下哪张图片是自行车?**")
print("A.")
display(Image.open("image.jpg"))
print("B.")
display(Image.open("image2.jpg"))
print("C.")
display(Image.open("image3.jpg"))

方案2:转ASCII字符画(适配所有控制台场景,包括Run窗口、外置终端)

如果需要在右键运行的Run窗口也显示图片,可以把图片转换为字符画输出,兼容性最高:

  1. 安装依赖:
pip install pillow
  1. 代码示例:
from PIL import Image

# 按亮度从暗到亮自定义字符集,可自行调整获得更好的显示效果
ASCII_CHARS = "@%#*+=-:. "

def image_to_ascii(image_path, output_width=100):
    # 打开图片转灰度
    img = Image.open(image_path).convert("L")
    # 调整宽高比避免字符画变形
    height_ratio = img.height / img.width / 2
    output_height = int(output_width * height_ratio)
    resized_img = img.resize((output_width, output_height))

    ascii_result = ""
    for y in range(output_height):
        for x in range(output_width):
            pixel_brightness = resized_img.getpixel((x, y))
            # 像素亮度映射到字符集
            ascii_result += ASCII_CHARS[int(pixel_brightness / 255 * (len(ASCII_CHARS) - 1))]
        ascii_result += "\n"
    return ascii_result

# 输出题目和选项
print("**请问以下哪张图片是自行车?**")
print("A.")
print(image_to_ascii("image.jpg"))
print("\nB.")
print(image_to_ascii("image2.jpg"))
print("\nC.")
print(image_to_ascii("image3.jpg"))

注意事项

  • 方案1仅在PyCharm左下角入口进入的「Python Console」中生效,右键运行脚本的Run窗口默认不支持原图渲染,只能用方案2
  • 字符画的显示效果可调整output_width参数、更换ASCII_CHARS的字符组合适配需求

内容的提问来源于stack exchange,提问作者Shane Wegmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:30:04