簡體   English   中英

我如何在 python 中直接截圖 base64

[英]how can i screenshot directely base64 in python

我想在不保存照片的情況下截屏並將其轉換為 base64 以將其保存在字典中。

def screen():
    global photo, numero_photo, photo_temporaire, photo_save
    time.sleep(3)
    position_screen = pyautogui.position()
    photo = pyautogui.screenshot(region = (position_screen[0] - 20, position_screen[1] - 20, 40, 40))

    with open(photo, 'rb') as imagefile:
        format_byte = base64.b64encode(imagefile.read())
        format_byte = str(format_byte)
        format_byte = format_byte.lstrip("b'")
        format_byte = format_byte.rstrip("'")
        photo_save.append(format_byte)
    
    print(photo_save)

我有這個錯誤:

  File "D:\Logiciel\Python\lib\tkinter\__init__.py", line 1921, in __call__        
    return self.func(*args)
  File "d:\Logiciel\programme\projet_bouclette\testbase64_7.py", line 23, in screen
    with open(photo, 'rb') as imagefile:
TypeError: expected str, bytes or os.PathLike object, not Image

您已經有Image object,而不是文件名。 PyAutoGui screenshot()文檔中:

調用screenshot()將返回一個圖像 object(有關詳細信息,請參閱 Pillow 或 PIL 模塊文檔)。

您可以將 object 轉換為base64 ,方法是將其“保存”到內存bytes object。 我在該主題上寫的較早答案改寫為 output 一個 PNG 圖像(這對於屏幕截圖可能更有效,具體取決於主題):

from io import BytesIO

photo = pyautogui.screenshot(region = (position_screen[0] - 20, position_screen[1] - 20, 40, 40))

output = BytesIO()
photo.save(output, format='PNG')
im_data = output.getvalue()

image_data = base64.b64encode(im_data).decode()
print(image_data)

PNG 適用於“常規”圖像數據,例如大多數操作系統上的平均 window 系統。 如果您的屏幕截圖包含視頻或照片應用程序,您可能希望使用'JPG'而不是'PNG'來將圖像保存為有損 JPEG 格式。

無論您做什么,都不要使用str()strip()將字節轉換為字符串 像上面一樣使用bytes.decode(..) Base64 數據始終是 ASCII 安全的,因此 UTF8 的默認編解碼器可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM