2

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

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • I don't get it. What is the reason that you don't use [`pygame.image.load()`](https://www.pygame.org/docs/ref/image.html#pygame.image.load) – Rabbid76 Jul 10 '19 at 18:16
  • Because you can't import png and jpg with the Pygame module. See this: https://www.pygame.org/docs/ref/image.html When you can tell me how I can import it although with Pygame I'm happy. – Spielekind005 Jul 10 '19 at 18:18
  • Nonsense, I do it almost every day. From your link *"[...] can support the following formats. JPG PNG [...]"* – Rabbid76 Jul 10 '19 at 18:21
  • By default, it can only load uncompressed BMP images. No, it can't load PNG only with the full build. What I found all called Pillow aka PIL the full build. When I run it with the Pygame import I get the error: Couldn't open myImage.png – Spielekind005 Jul 10 '19 at 18:22
  • Can you look at the Image above and please tell me what I do wrong. – Spielekind005 Jul 10 '19 at 18:26

1 Answers1

5

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)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174