0

Hi I'm trying to load my image from Pillow into Pygame using BytesIO.

from PIL import Image
import io

pilImage = Image.open('AgV6E.png')
temp_io = io.BytesIO()
pilImage.save(temp_io, format='PNG')
pygame.image.load(temp_io)

I get the following error: pygame.image.load(temp_io) pygame.error: Unsupported image format

Strangely enough though simply saving to png works.

from PIL import Image
import io

pilImage = Image.open('AgV6E.png')
pilImage.save("test.png", format='PNG')
pygame.image.load("test.png")

Anybody know how to fix this?

Flare
  • 71
  • 1
  • 7
  • try with: `pygame.image.load(temp_io, namehint="test.png")` – eyllanesc Nov 09 '21 at 04:59
  • @eyllanesc Unfortunately that doesn't work either. I still get the same error. Perhaps its a PyGame error? – Flare Nov 09 '21 at 05:42
  • What does `pygame.image.get_extended()` return? – Jan Wilamowski Nov 09 '21 at 06:10
  • You can load the image directly with [`pygame.image.fromstring`](https://www.pygame.org/docs/ref/image.html#pygame.image.fromstring). See [PIL and pygame.image](https://stackoverflow.com/questions/25202092/pil-and-pygame-image/64182629#64182629) – Rabbid76 Nov 09 '21 at 06:12
  • @JanWilamowski it returned true. – Flare Nov 09 '21 at 06:16
  • @Rabbid76 I tried this but with certain images it would return completely white or the background colour would return some strange colour. Possibly something with the alpha-channels or lack of them. – Flare Nov 09 '21 at 06:27
  • 1
    @Flare Seems to be a pygame bug. Why do you not use [pygame.image.load](https://www.pygame.org/docs/ref/image.html)? – Rabbid76 Nov 09 '21 at 07:05
  • @Rabbid76 The loading of the image in pil is just an example. In reality I'm going to add glow effects, blur filters, etc. in PIL before sending it back to pygame for blitting. – Flare Nov 09 '21 at 08:32

1 Answers1

1

Turns out I needed to run BytesIO.seek(0) before running load to set the stream position back to zero. Here is the updated code.

from PIL import Image
import io

pilImage = Image.open('AgV6E.png')
temp_io = io.BytesIO()
pilImage.save(temp_io, format='PNG')
temp_io.seek(0)
pygame.image.load(temp_io)

seek(0) is probably what allowed it to be read correctly as it moved the stream position back to the beginning. Thanks to Starbuck5 letting me know the answer.

Flare
  • 71
  • 1
  • 7
  • Seems good, However, It would be better if you can explain what seek() method does, to simplify further. – Sourabh Desai Nov 09 '21 at 06:30
  • 1
    @SourabhDesai ok sounds good, I've updated the answer with a bit more info. – Flare Nov 09 '21 at 06:41
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 09 '21 at 07:42