python将图像保存在ram中而不保存到硬盘?

2024-10-01 05:04:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个屏幕放大程序,这样我就可以用我的视力看到屏幕了。你知道吗

import pyautogui
import pygame
import PIL
from PIL import Image

pygame.init()

LocationLeft = 50
LocationTop = 50
LocationWidth = 100
LocationHeight = 100

Magnification = 3

gameDisplay = pygame.display.set_mode((LocationWidth * Magnification , LocationHeight * Magnification ))

crashed = False

ImageFileName="ScreenLarger.png"

try:
    while not crashed:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                crashed = True

        x, y = pyautogui.position()

        LocationLeft = x - 25
        LocationTop = y - 25

        im = pyautogui.screenshot(imageFilename=ImageFileName ,region=(LocationLeft,LocationTop, LocationWidth, LocationHeight))

        img = Image.open(ImageFileName)
        img = img.resize((LocationWidth * Magnification, LocationHeight * Magnification))
        img.save(ImageFileName)

        theimg = pygame.image.load(ImageFileName)

        gameDisplay.blit(theimg,(0,0))

        pygame.display.update()

except KeyboardInterrupt:
    print('\n')

它工作得很好,你可以使用它,问题是它与硬盘互动4次每次迭代,我不认为这是最佳做法,因为那些没有固态驱动器它会增加磨损和损坏驱动器。那么,如何将图像保存在ram中它所属的位置呢?你知道吗


Tags: imageimporteventimgpil屏幕pygamepyautogui
1条回答
网友
1楼 · 发布于 2024-10-01 05:04:38

那你为什么要把它保存到一个文件里?你知道吗

^{}只有在传递文件名时才保存到文件,否则,它返回PIL.Image。只是不要要求它保存到一个文件。你知道吗

Pygame有一个函数^{}。你知道吗

这样,您就可以截图并将其转换为pygame surface:

screenshot = pyautogui.screenshot(region=(LocationLeft,LocationTop, LocationWidth, LocationHeight))
image = pygame.image.fromstring(screenshot.tobytes(), screenshot.size, screenshot.mode)

然后直接将其blit到screen,而无需将其保存到文件中。你知道吗

^{}返回图像的原始字节,这就是pygame所说的“字符串”,而不是同一件事,bytes是一个函数,它存在于python库中,全局存在,因此单词“bytes”不能真正用作变量名而不隐藏该函数,更常见的情况是(仅在python中!),处理二进制数据时-string表示bytes。你知道吗

^{}返回图像的维度,这是pygame函数所期望的。你知道吗

^{}返回图像的格式,pygame还需要从原始字节重建真实图像。你知道吗

如果您不需要翻转图像(这由您自己来决定),您应该使用^{}而不是^{},这样会更快,因为它不会复制任何数据,而是直接使用PIL图像字节。你知道吗

相关问题 更多 >