9

我正在使用 PIL 透视地转换屏幕的一部分。原始图像数据是一个 pygame Surface,需要转换为 PIL 图像。

因此,我找到了为此目的而存在的 pygame 的 tostring 函数。

然而结果看起来很奇怪(见附件截图)。这段代码出了什么问题:

rImage = pygame.Surface((1024,768))

#draw something to the Surface
sprite = pygame.sprite.RenderPlain((playboard,))
sprite.draw(rImage)

pil_string_image = pygame.image.tostring(rImage, "RGBA",False)
pil_image = Image.fromstring("RGBA",(660,660),pil_string_image)

我究竟做错了什么?

pygame表面到pil图像转换

4

1 回答 1

8

As I noted in a comment, pygame documentation for pygame.image.fromstring(string, size, format, flipped=False) says “The size and format image must compute the exact same size as the passed string buffer. Otherwise an exception will be raised”. Thus, using (1024,768) in place of (660,660), or vice versa – in general, the same dimensions for the two calls – is more likely to work. (I say “more likely to work” instead of “will work” because of I didn't test any cases.)

The reason for suspecting a problem like this: The strange look of part of the image resembles a display screen which is set to a raster rate it can't synchronize; ie, lines of the image start displaying at points other than at the left margin; in this case because of image line lengths being longer than display line lengths. I'm assuming the snowflakes are sprites, generated separately from the distorted image.

于 2013-01-06T00:17:00.613 回答