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

python在ram中保留图像而不保存到硬盘?,python,image,pygame,python-imaging-library,pyautogui,Python,Image,Pygame,Python Imaging Library,Pyautogui,我做了一个屏幕放大程序,这样我就可以用我的视力看到屏幕了,我做了这个 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((

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

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中它所属的位置呢

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

仅当您将文件名传递到应保存的位置时,才会保存到文件,否则,它将返回
PIL.Image
。只是不要要求它将其保存到文件中

Pygame有一个函数

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

screenshot=pyautogui.screenshot(region=(LocationLeft、LocationTop、LocationWidth、LocationHeight))
image=pygame.image.fromstring(screenshot.tobytes(),screenshot.size,screenshot.mode)
然后直接将其blit到屏幕,而无需将其保存到文件中

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

返回图像的维度,这是pygame函数所期望的

返回图像的格式,pygame还需要从原始字节重建真实图像


如果您不需要翻转图像(这由您自己决定),您应该使用,而不是,这将更快,因为它不会复制任何数据,并且将直接使用PIL图像字节。

查看ByteIO:无需责备自己,每个人一开始都是个傻瓜:)你阅读教程并担心IO调用的数量,这是你做得很好的最好迹象。很高兴有你在这里!