11

Is there a way I can take a screenshot of the right half of my pygame window?

I'm making a game using pygame and I need to take a snapshot of the screen but not the whole screen, just the right half.

I know of:

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

But that will include the entire screen in the image.

Is there a way I can take a screenshot of the right half of my pygame window?

Maybe by changing the area that it includes somehow? I've googled it but couldn't find anything I was thinking maybe I could use PIL to crop it, but that seems like a lot of additional work.

If it's not possible, can anyone tell me the easiest way for me to crop the picture of the whole screen?

4

4 回答 4

16

如果您总是希望屏幕截图与屏幕的同一部分相同,则可以使用subsurface. http://www.pygame.org/docs/ref/surface.html#pygame.Surface.subsurface

rect = pygame.Rect(25, 25, 100, 50)
sub = screen.subsurface(rect)
pygame.image.save(sub, "screenshot.jpg")

在这种subsurface情况下会很好地工作,因为对父表面(screen在这种情况下)的任何更改也将应用于次表面。

如果您希望能够指定屏幕的任意部分来截取屏幕截图(因此,每次都不是相同的矩形),那么创建一个新的表面可能会更好,将屏幕的所需部分blit到那个面,然后保存。

rect = pygame.Rect(25, 25, 100, 50)
screenshot = pygame.Surface(100, 50)
screenshot.blit(screen, area=rect)
pygame.image.save(screenshot, "screenshot.jpg")
于 2013-06-24T15:42:17.737 回答
0

这并不完全适用于我的 Python 3.7.4 系统。这是一个有效的版本:

rect = pygame.Rect(25, 25, 100, 50)
sub = screen.subsurface(rect)
screenshot = pygame.Surface((100, 50))
screenshot.blit(sub, (0,0))
pygame.image.save(screenshot, "screenshot.jpg")
于 2020-03-05T14:46:55.690 回答
0
import pygame
import sys


screen = pygame.display.set_mode((400, 500))
clock = pygame.time.Clock()


def grab(x, y, w, h):
    "Grab a part of the screen"
    # get the dimension of the surface
    rect = pygame.Rect(x, y, w, h)
    # copy the part of the screen
    sub = screen.subsurface(rect)
    # create another surface with dimensions
    # This is done to unlock the screen surface
    screenshot = pygame.Surface((w, h))
    screenshot.blit(sub, (0, 0))
    return screenshot


def blit(part, x, y):
    screen.blit(part, (x, y))


def quit():
    pygame.quit()
    sys.exit()


def start():
    # shows half the screen
    blit(back, 0, 0)
    # and the other half copied
    sub = grab(50, 0, 75, 250)
    blit(sub, 200, 0)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    quit()
        pygame.display.update()
        clock.tick(60)


back = pygame.image.load("img\\back.png")

start()
于 2020-07-10T08:00:56.840 回答
-2

我会做类似的事情:

example = pygame.Surface(screen.get_width()/2, 0)

然后稍后当您要截屏时,请执行以下操作:

pygame.image.save(example, "example.jpg")

于 2014-08-09T04:17:44.743 回答