![](/img/trans.png)
[英]How to load a image into a label without saving to hard drive python Tkinter
[英]python keeping a image in ram not saving to hard drive?
我做了一個屏幕放大程序,所以我可以用我的視力看到屏幕,並做了這個。
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所屬的位置?
為什么要將它保存到文件中呢?
pyautogui.screenshot
僅在您傳遞應保存的文件名時保存到文件,否則返回PIL.Image
。 只是不要求它將其保存到文件中。
Pygame有一個函數pygame.image.fromstring(string, size, format, flipped=False) -> Surface
。
這樣,您可以截取屏幕截圖並將其轉換為pygame表面:
screenshot = pyautogui.screenshot(region=(LocationLeft,LocationTop, LocationWidth, LocationHeight))
image = pygame.image.fromstring(screenshot.tobytes(), screenshot.size, screenshot.mode)
然后直接將其blit到屏幕,而無需將其保存到文件中。
.tobytes()
返回一個圖像的原始字節,這就是pygame所說的“字符串”,而不是同一個東西, bytes
是一個存在於python庫中的函數,全局,因此單詞“bytes”不能真正用作在處理二進制數據時,變量名稱沒有遮蔽該函數(通常只在Python中) - string
表示 bytes
。
.size
返回圖像的尺寸,這是pygame函數所期望的。
.mode
返回圖像的格式,pygame還需要從原始字節重建真實圖像。
如果您不需要翻轉圖像(這是為了讓您弄清楚),您應該使用pygame.image.frombuffer
而不是pygame.image.fromstring
,這將更快,因為它不會復制任何數據和將直接使用PIL圖像字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.