这是我的密码:
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地段。
发布于 2016-05-01 12:40:21
原因是行pygame.image.fromstring(..., 'P'),其中'P‘表示8位编码。字符串文档中的游戏映像声明“\"P\”格式只创建一个8位的表面,但是颜色映射将全部是黑色的。“
我通过手动复制PIL图像的颜色调色板来解决这个问题。代码片段如下:
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中读取地图块)在内存中创建的。
代码示例如下:
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。
https://stackoverflow.com/questions/32102851
复制相似问题