简体   繁体   English

如何将pygame曲面转换为PIL图像?

[英]How to convert a pygame Surface to a PIL Image?

I'm using PIL to transform a portion of the screen perspectively. 我正在使用PIL透视变换屏幕的一部分。 The original image-data is a pygame Surface which needs to be converted to a PIL Image. 原始图像数据是pygame曲面,需要将其转换为PIL图像。

Therefore I found the tostring-function of pygame which exists for that purpose. 因此,我发现了为此目的而存在的pygame的tostring函数。

However the result looks pretty odd (see attached screenshot). 但是结果看起来很奇怪(请参阅随附的屏幕截图)。 What is going wrong with this code: 这段代码出了什么问题:

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)

What am I doing wrong? 我究竟做错了什么?

pygame表面到pil图像转换

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. 正如我在评论中指出的, pygame.image.fromstring pygame.image.fromstring(string, size, format, flipped=False) pygame文档说:“大小和格式图像必须计算出与传递的字符串缓冲区完全相同的大小。 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. 因此,使用(1024,768)代替(660,660),反之亦然-通常,两个调用的尺寸相同-更有可能工作。 (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. 我假设雪花是精灵,与扭曲的图像分开生成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM