2

I need to do the following. I loaded an obj model using OBJFileLoader and rendered it to a window. How can I save the rendered scene as a picture? Is it possible to do this without even showing the window?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
SomVolodya
  • 23
  • 3

1 Answers1

6

You can save a pygame.Surface object, object as the Surface associated with the screen with pygame.image.save():

This will save your Surface as either a BMP, TGA, PNG, or JPEG image.

screen = pygame.display.set_mode((w, h))

# [...]

pygame.image.save(screen , "screenshot.jpg")

However, this doesn't work for pygame.OPENGL Surfaces. You must read the framebuffer with glReadPixels before the display is updated (before pygame.display.flip() or pygame.display.update()). Use pygame.image.fromstring() to create new Surfaces from the buffer. Finally, save the Surface to a file:

screen = pygame.display.set_mode((w, h), pygame.DOUBLEBUF | pygame.OPENGL)

# [...]

size = screen.get_size()
buffer = glReadPixels(0, 0, *size, GL_RGBA, GL_UNSIGNED_BYTE)
pygame.display.flip()

screen_surf = pygame.image.fromstring(buffer, size, "RGBA")
pygame.image.save(screen_surf, "screenshot.jpg")
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Is it possible to somehow hide the window so that it is not displayed? – SomVolodya Feb 16 '21 at 18:02
  • @SomVolodya See [`pygame.display`](https://www.pygame.org/docs/ref/display.html): *"`pygame.HIDDEN` window is opened in hidden mode"* e.g.: `pygame.display.set_mode((w, h), pygame.DOUBLEBUF | pygame.OPENGL | pygame.HIDDEN)` (since Pygame version 2.0) – Rabbid76 Feb 16 '21 at 18:07