Home > Net >  problems with PIL
problems with PIL

Time:11-21

Today I tried to switch pygame's image.load() to Pil's Image.open() but (as usual) I got problems. At the beginning of the code I have this fragment with pygame's image.load():

class Gamesprite():
    def __init__(self,img,x,y,width,height,speed):
        sprite.Sprite.__init__(self)
        self.image = transform(image.load(img), (width, height))

The fragment of code below is one of 4 fragments (left, right, up down) where I experimentally added image = Image.open('image.png') but code got crashed.

class Player(Gamesprite):
    def control(self):
        keys=key.get_pressed()
        if keys[K_LEFT]:
            hero_img = Image.open('hero_left.png')
            self.rect.x -= self.speed
            for wall in list_wall:
                if sprite.collide_rect(self,wall):
                    self.rect.x  = self.speed*1.1

After starting code I get:

File "e:\VSCode projects\lab2.1.py", line 60, in <module>
    player = Player(hero_img,     tiles,    tiles,    int(tiles*0.87),tiles, tiles//10)
  File "e:\VSCode projects\lab2.1.py", line 15, in __init__
    self.image = transform(image.load(img), (width, height))
TypeError: not a file object

If you know how to solve this problem, save image in variable "hero_img", and make character switch his image while pressing button, please help! :(

CodePudding user response:

From the official documentation, the result of pygame's image.load is a pygame.Surface object. The result of PIL's Image.open function is a PIL.Image.Image object. They are not interchangeable. You can try to convert the PIL image into an array, and then copy it to the pygame surface.

Here are some helpful links:

https://stackoverflow.com/a/1095878/5166365 https://www.pygame.org/docs/ref/surfarray.html#pygame.surfarray.blit_array

  • Related