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

如何在Pygame中使用RGBA值列表直接显示修改后图像无需本地保存

你不需要将修改后的图像保存到本地,也无需直接操作new_image列表,你已经通过img.putdata(new_image)将修改后的像素写入了Pillow的Image对象,直接将该对象转换为Pygame支持的Surface对象即可直接使用。

首先先修复你现有代码的一个逻辑bug:两个if判断是并列关系,会导致匹配第一个if条件的像素被重复添加两次,最终像素列表长度是原图的2倍,引发报错,需要将第二个if改为elif。

完整实现代码如下:

from PIL import Image
import pygame as pg

# 初始化Pygame
pg.init()
screen = pg.display.set_mode((800, 600))

# 读取并修改图像(和你的逻辑一致,修复了判断分支的问题)
img = Image.open("Assets/image.png")
img = img.convert("RGBA")
d = img.getdata()
new_image = []
for item in d:
    if item[:3] == (0, 0, 0):
        # 纯黑色替换为完全透明
        new_image.append((255, 255, 255, 0))
    elif item[:3] == (23, 186, 255):
        # 特定蓝色替换为红色,保留原透明度
        new_image.append((255, 38, 49, item[3]))
    else:
        new_image.append(item)
img.putdata(new_image)

# 核心转换逻辑:Pillow Image 转 Pygame Surface,无需本地存盘
width, height = img.size
image_bytes = img.tobytes("raw", "RGBA")
pg_image = pg.image.frombuffer(image_bytes, (width, height), "RGBA")

# 正常渲染使用即可
running = True
while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
    screen.fill((255, 255, 255))
    # 把转换后的图像绘制到屏幕坐标(100,100)处
    screen.blit(pg_image, (100, 100))
    pg.display.flip()

pg.quit()

如果你确实需要直接从new_image的RGBA元组列表生成Pygame图像,也可以将列表扁平化转为字节后传入frombuffer,但上述方案已经是性能最优的实现方式,完全满足你的需求,程序关闭后不会生成任何本地缓存文件。

内容的提问来源于stack exchange,提问作者Michael Stevens

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:36:04