首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python游戏如何显示8位图像

Python游戏如何显示8位图像
EN

Stack Overflow用户
提问于 2015-08-19 18:20:28
回答 1查看 1.1K关注 0票数 1

这是我的密码:

代码语言:javascript
复制
from PIL import ImageGrab
import pygame

i = ImageGrab.grab()
i = i.quantize(256)
xy = i.getbbox()
pd = pygame.display.set_mode((xy[2],xy[3]))
new_img = pygame.image.fromstring(i.tostring(),(xy[2],xy[3]),'P')
clock = pygame.time.Clock()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
    pd.blit(new_img,(0,0))
    pygame.display.flip()
    clock.tick(30)

我正在获得黑屏幕,请帮助解决我的issue.thanks地段。

EN

回答 1

Stack Overflow用户

发布于 2016-05-01 12:40:21

原因是行pygame.image.fromstring(..., 'P'),其中'P‘表示8位编码。字符串文档中的游戏映像声明“\"P\”格式只创建一个8位的表面,但是颜色映射将全部是黑色的。“

我通过手动复制PIL图像的颜色调色板来解决这个问题。代码片段如下:

代码语言:javascript
复制
img = PIL.Image.open(...)  # read an 8-bit image
surface = pygame.image.fromstring(img.tobytes(), img.size, img.mode)  # img.mode is 'P'

new_palette = []
rgb_triplet = []
for rgb_value in img.getpalette():
    # this loop could be improved, but you get the idea
    rgb_triplet.append(rgb_value)

    if len(rgb_triplet) == 3:
        new_palette.append((rgb_triplet[0], rgb_triplet[1], rgb_triplet[2]))
        rgb_triplet = []

surface.set_palette(new_palette)

重要:为了调用surface.set_palette,您必须先调用pygame.init(),否则会出现异常。

另一个选项:

我解决这个问题的另一种方法是把图像写到磁盘上,然后直接加载到游戏表面。这保留了原来的调色板。请注意,这对我有用,因为我使用的PIL映像根本不是从磁盘读取的,而是通过从URL读取数据(在本例中是从OpenStreetMap中读取地图块)在内存中创建的。

代码示例如下:

代码语言:javascript
复制
url = "http://a.tile.openstreetmap.org/{0}/{1}/{2}.png"  # serves up 8-bit PNGs
zoom = 10
tilex = 1
tiley = 1

tile_url = url.format(zoom, tilex, tiley)
imgstr = urllib2.urlopen(tile_url).read()
tile_img = PIL.Image.open(StringIO.StringIO(imgstr))

temp_filename = "%s.%s.%s" % (zoom, tilex, tiley)
tile_img.save(temp_filename)

surface = pygame.image.load(temp_filename)

显然,这不是一个高性能的解决方案,因为IO。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32102851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档