Search code examples
pythonimagepython-3.xpygamescreenshot

Take screenshot then blit it


Is there a way to take a screenshot (a copy of the previous frame blitted) with pygame from the GUI, assign it to a surface variable and blit it? Without saving the screenshot to a file, then loading it, and finally blitting it,

import pygame, os

pygame.init()
screen = pygame.display.set_mode((800, 400))

def TakeScreenShot(screen):
    pygame.image.save(screen, 'ScreenShot.png')
    pic = pygame.image.load(os.path.join('ScreenShot.png')).convert()

    return pic

pic = TakeScreenShot(screen)
screen.blit(pic, [0,0])
pygame.display.flip()

The saving screenshot then loading seems really unneccsary...is there a method to bypass this and directly blit the screenshot taken to the GUI?

I.e., something such as,

import pygame, os

pygame.init()
screen = pygame.display.set_mode((800, 400))
pic = screen.getLastFrameBlitted()
screen.blit(pic, [0,0])
pygame.display.flip()

Solution

  • You can take a copy of the screen anytime you want and save it in a variable.

    screenshot = screen.copy()
    

    screen is just a regular Surface object and can be treated as such. Blitting the screenshot is done as usual

    screen.blit(screenshot, (0, 0))