How to display Images loaded with Pillow with Pygame in Python 3.7?

Question:

I imported an image to my project using

from PIL import Image
myImage = Image.open("myImageDirectory.png")

So myImage is now imported as a png file. But I want to display it to the Screen using Pygame. Normally I use

import pygame
win = pygame.display.set_mode((500, 500))
win.blit(myImage, (50, 50))

Now I get the Error that the function needs a surface, not a png File.
Has anyone an idea how I can convert the image to a surface or how I can display it?

I tried not much yet​ because I didn’t found anything that could solve my problem.

Edit:

What is wrong with this way that I get the error: Couldn’t open bg.png

Asked By: Spielekind005

||

Answers:

See PIL and pygame.image. Use Image.tobytes() get the image data as a bytes object and pygame.image.fromstring() to load the data to an pygame.Surface object:

from PIL import Image
import pygame
pilImage = Image.open("myImageDirectory.png")
myImage = pygame.image.fromstring(pilImage.tobytes(), pilImage.size, pilImage.mode)
Answered By: Rabbid76