Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a pygame Surface to a PIL Image?

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

like image 411
Hedge Avatar asked Jan 05 '13 21:01

Hedge


People also ask

How do I convert an image to pygame surface?

Step 1: First, import the libraries Image and Pygame. Step 2: Now, take the colors as input that you want to use in the game. Step 3: Then, construct the GUI game. Step 4: Further, set the dimensions of your GUI game.

How do I Pil an image?

Image. open() Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method).

Can pygame use JPG files?

Pygame is able to load images onto Surface objects from PNG, JPG, GIF, and BMP image files.


1 Answers

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.

like image 172
James Waldby - jwpat7 Avatar answered Sep 22 '22 15:09

James Waldby - jwpat7