Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


Python Windows watch clipboard

19 Dec 2022 »
import time
import sys
import os
import traceback
import io
sys.path.append(os.path.abspath("SO_site-packages"))
from PIL import ImageGrab
import base64
import requests

def dupi_up(imgb64, path="test"):
    payload = {
        "image64": imgb64,
        "path": path,
    }
    rs = requests.post("http://api-dupi2.local.com/recv", json=payload)
    return rs.text.strip()

# get image from clipboard in python
# https://www.youtube.com/watch?v=vom14HdD594&ab_channel=codethemall

#https://stackoverflow.com/questions/48229318/how-to-convert-image-pil-into-base64-without-saving/48229407
#by @Taha Mahjoubi
def img_to_base64_str(img):
    buffered = io.BytesIO()
    img.save(buffered, format="PNG")
    buffered.seek(0)
    img_byte = buffered.getvalue()
    img_str = "data:image/png;base64," + base64.b64encode(img_byte).decode()
    return img_str

import pyperclip

recent_value = ""
while True:
    try:
        tmp_value = pyperclip.paste()
        try:
            im = ImageGrab.grabclipboard()
        except KeyboardInterrupt:
            break
        except:
            time.sleep(1)
            continue
        if im:
            #im.save("test.png", "PNG")
            imb64 = img_to_base64_str(im)
            tmp_value = imb64
            #pyperclip.copy(imb64)
        if tmp_value != recent_value:
            recent_value = tmp_value
            if recent_value.startswith("data:image"):
                serial = dupi_up(recent_value, "awspro")
                pyperclip.copy(f"![200x](http://api-dupi2.local.com/image/{serial})")
            print("Value changed: %s" % str(recent_value)[:20])
        time.sleep(0.1)
    except KeyboardInterrupt:
        break
    except:
        traceback.print_exc()
        time.sleep(1)