9

I'm using PIL to transform a portion of the screen perspectively. The original image-data is a pygame Surface which needs to be converted to a PIL Image.

Therefore I found the tostring-function of pygame which exists for that purpose.

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 surface to pil image conversion

Hedge
  • 16,142
  • 42
  • 141
  • 246
  • 1
    What's it look like if you put (1024,768) in place of (660,660), or vice versa? – James Waldby - jwpat7 Jan 05 '13 at 21:43
  • [pygame docs](http://www.pygame.org/docs/ref/image.html#pygame.image.fromstring) about pygame.image.fromstring(string, size, format, flipped=False) say “The size and format image must compute the exact same size as the passed string buffer. Otherwise an exception will be raised” but beyond that I don't know how it works. – James Waldby - jwpat7 Jan 05 '13 at 21:52
  • please add your guess as the answer so I can mark the question solved! – Hedge Jan 05 '13 at 23:06

1 Answers1

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.

James Waldby - jwpat7
  • 8,593
  • 2
  • 22
  • 37