0

I would like to screenshot without saving the photo and transform it into base64 to save it in a dictionary.

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)

and I have this error:

  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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
bluehat
  • 3
  • 1

1 Answers1

1

You already have an Image object, not a filename. From the PyAutoGui screenshot() documentation:

Calling screenshot() will return an Image object (see the Pillow or PIL module documentation for details).

You can convert that object to base64 by 'saving' it to an in-memory bytes object. Adapting an earlier answer I wrote on the subject to output a PNG image instead (which might be more efficient for screenshots, depending on the subject matter):

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 works great for 'regular' image data, such as your average window system on most operating systems. If your screenshots contain video or photo apps, you may want to use 'JPG' instead of 'PNG' to save the image in the lossy JPEG format instead.

Whatever you do do not use str() and strip() to convert from bytes to strings. Use bytes.decode(..) as I do above. Base64 data is always ASCII-safe so the default codec of UTF8 will do fine.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343