예제 #1
0
파일: main.py 프로젝트: Ziuan/SSLooker
def screenshot(save_path, filename, app=None):
    filepath = save_path + "\\" + filename
    if not app:
        app = win32gui.GetDesktopWindow()
    try:
        win32gui.SetForegroundWindow(app)
    except:
        pass
    bbox = win32gui.GetWindowRect(app)
    img = ImageGrab.grab(bbox)
    # img.save(filepath + ".jpeg", 'jpeg')
    # with Image.open(filepath + ".jpeg") as opened:
    text = pytesseract.image_to_string(img)
    tt = pytesseract.image_to_string(img, 'eng', '--oem 1')
    if ('demolished' in text):
        print('HIT1')
    if ('demolished' in tt):
        print('HIT2')
    return

    l, t, r, b = win32gui.GetWindowRect(app)
    h = b - t
    w = r - l
    hDC = win32gui.GetWindowDC(app)
    myDC = win32ui.CreateDCFromHandle(hDC)
    newDC = myDC.CreateCompatibleDC()

    myBitMap = win32ui.CreateBitmap()
    myBitMap.CreateCompatibleBitmap(myDC, w, h)

    newDC.SelectObject(myBitMap)

    sleep(.2)  # lame way to allow screen to draw before taking shot
    newDC.BitBlt((0, 0), (w, h), myDC, (0, 0), win32con.SRCCOPY)
    myBitMap.Paint(newDC)

    myBitMap.SaveBitmapFile(newDC, filepath + ".bmp")
    img = Image.open(filepath + ".bmp")
    new_img = img.resize((256, 256))
    new_img.save(filepath + ".jpeg", 'jpeg')
예제 #2
0
    def __init__(
            self,
            config_file='configs/config.txt',
            num_runs=100,
            #class_name="Win32Window0",
            # 新引擎中类名为Win32Window
            class_name="Win32Window",
            title_name="阴阳师-网易游戏"):
        # Find the hwnd of the window
        self.hwnd = win32gui.FindWindow(class_name, title_name)
        # Set the program to forground
        #win32gui.SetForegroundWindow(hwnd)
        left, top, right, bottom = win32gui.GetClientRect(self.hwnd)
        # Calculat the size of the window
        self.width = right - left
        self.height = bottom - top
        # Create DCs
        self.hwndDC = win32gui.GetWindowDC(self.hwnd)
        self.mfcDC = win32ui.CreateDCFromHandle(self.hwndDC)
        self.saveDC = self.mfcDC.CreateCompatibleDC()
        # Create Bit Map
        self.saveBitMap = win32ui.CreateBitmap()
        self.saveBitMap.CreateCompatibleBitmap(self.mfcDC, self.width,
                                               self.height)
        self.saveDC.SelectObject(self.saveBitMap)

        # Initialize configuration for target pixel and clicking area
        print("配置文件config_xxx.txt(默认%s,输入xxx):" % config_file, end="")
        config_file_input = input()
        config_file = "configs/config_" + config_file_input + ".txt" \
                if config_file_input != "" else config_file
        self.configs = self.read_file(config_file)

        # Get the input for total running time
        print("运行次数(默认%d):" % num_runs, end="")
        num_runs_input = input()
        num_runs = int(num_runs_input) if num_runs_input != "" else num_runs
        # Initialize progressing bar with the total running times
        self.pbar = tqdm(total=num_runs, ascii=True)
        self.pbar_time = 0
예제 #3
0
    def GrabScreen(self, region=None):
        """Quickly grab screen reigon using win32 libs

        Keyword Arguments:
            region {[tuple]} -- [left_offset, top_offset, xreigon, yreigon] (default: {None})

        Returns:
            [type] -- [cv2 image]
        """
        hwin = win32gui.GetDesktopWindow()

        if region:
            left, top, x2, y2 = region
            width = x2 - left + 1
            height = y2 - top + 1
        else:
            width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
            height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
            left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
            top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

        hwindc = win32gui.GetWindowDC(hwin)
        srcdc = win32ui.CreateDCFromHandle(hwindc)
        memdc = srcdc.CreateCompatibleDC()
        bmp = win32ui.CreateBitmap()
        bmp.CreateCompatibleBitmap(srcdc, width, height)
        memdc.SelectObject(bmp)
        memdc.BitBlt((0, 0), (width, height), srcdc, (left, top),
                     win32con.SRCCOPY)

        signedIntsArray = bmp.GetBitmapBits(True)
        img = np.fromstring(signedIntsArray, dtype='uint8')
        img.shape = (height, width, 4)

        srcdc.DeleteDC()
        memdc.DeleteDC()
        win32gui.ReleaseDC(hwin, hwindc)
        win32gui.DeleteObject(bmp.GetHandle())

        return img
예제 #4
0
def get_window_shot(hwnd):
    # 对后台应用程序截图,程序窗口可以被覆盖,但如果最小化后只能截取到标题栏、菜单栏等。

    # 使用自定义的窗口边缘和大小设置
    dx = config.getint("Device", "EdgeOffsetX")
    dy = config.getint("Device", "EdgeOffsetY")
    w = config.getint("Device", "MainWidth")
    h = config.getint("Device", "MainHeight")
    window_w, window_h = detect_window_size(hwnd)
    if dx + w > window_w or dy + h > window_h:
        raise ValueError("截图区域超出窗口! 请检查配置文件")
    # logger.debug("截图: %dx%d at %dx%d", w, h, dx, dy)

    # 返回句柄窗口的设备环境、覆盖整个窗口,包括非客户区,标题栏,菜单,边框
    hwndDC = win32gui.GetWindowDC(hwnd)
    # 创建设备描述表
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # 创建内存设备描述表
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建位图对象
    saveBitMap = win32ui.CreateBitmap()
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    saveDC.SelectObject(saveBitMap)
    # 截图至内存设备描述表
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (dx, dy), win32con.SRCCOPY)
    # 获取位图信息
    bmpinfo = saveBitMap.GetInfo()
    bmpdata = saveBitMap.GetBitmapBits(True)
    # 生成图像
    image_data = np.frombuffer(bmpdata, "uint8")
    image_data = image_data.reshape(
        (bmpinfo["bmHeight"], bmpinfo["bmWidth"], 4))
    image_data = cv.cvtColor(image_data, cv.COLOR_BGRA2BGR)
    # 内存释放
    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)

    return image_data
예제 #5
0
    def screen_shot(self):
        """\
        Take a screenshot of the desktop.
        Returns True on success, False on failure.

        :rtype: bool
        """

        try:
            hwnd = win32gui.GetDesktopWindow()

            vscreenwidth = win32api.GetSystemMetrics(78)
            vscreenheight = win32api.GetSystemMetrics(79)
            vscreenx = win32api.GetSystemMetrics(76)
            vscreeny = win32api.GetSystemMetrics(77)

            mfcDC = win32ui.CreateDCFromHandle(win32gui.GetWindowDC(hwnd))
            saveDC = mfcDC.CreateCompatibleDC()

            saveBitMap = win32ui.CreateBitmap()
            saveBitMap.CreateCompatibleBitmap(mfcDC, vscreenwidth,
                                              vscreenheight)
            saveDC.SelectObject(saveBitMap)
            saveDC.BitBlt((0, 0), (vscreenwidth, vscreenheight), mfcDC,
                          (vscreenx, vscreeny), win32con.SRCCOPY)

            bmpinfo = saveBitMap.GetInfo()
            bmpstr = saveBitMap.GetBitmapBits(True)

            import Image
            im = Image.frombuffer('RGB',
                                  (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
                                  bmpstr, 'raw', 'BGRX', 0, 1)
            im.save('pyFetch-' + re.sub(":", "-", str(datetime.now())) +
                    ".png")

            return True

        except:
            return False
예제 #6
0
def capture_inactive_window(hwnd, client_area_only=True):
    """指定窗口截图

    http://stackoverflow.com/questions/19695214/python-screenshot-of-inactive\
            -window-printwindow-win32gui

    需要做黑屏判断,printwindow失败会得到一个黑色的图
    """
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)

    w = right - left
    h = bottom - top

    srcdc = win32gui.GetWindowDC(hwnd)
    memdc = win32ui.CreateDCFromHandle(srcdc)
    destdc = memdc.CreateCompatibleDC()

    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(memdc, w, h)
    destdc.SelectObject(bmp)

    windll.user32.PrintWindow(hwnd, destdc.GetSafeHdc(), 1 if client_area_only\
            else 0)

    bmp_info = bmp.GetInfo()
    bmp_bits = bmp.GetBitmapBits(True)

    # Only works in 32bit mode,
    # 虚拟机下有可能图形不是在 32 位模式的
    im = Image.frombuffer('RGB', (bmp_info['bmWidth'], bmp_info['bmHeight']),
                          bmp_bits, 'raw', 'BGRX', 0, 1)

    win32gui.DeleteObject(bmp.GetHandle())
    destdc.DeleteDC()
    memdc.DeleteDC()
    win32gui.ReleaseDC(hwnd, srcdc)

    windll.user32.UpdateWindow(hwnd)

    return im
def get_icon(PATH, size):
    SHGFI_ICON = 0x000000100
    SHGFI_ICONLOCATION = 0x000001000
    SHGFI_USEFILEATTRIBUTES = 0x000000010
    if size == "small":
        SHIL_SIZE = 0x00001
    elif size == "large":
        SHIL_SIZE = 0x00002
    else:
        raise TypeError(
            "Invalid argument for 'size'. Must be equal to 'small' or 'large'")

    ret, info = shell.SHGetFileInfo(
        PATH, 0,
        SHGFI_ICONLOCATION | SHGFI_ICON | SHIL_SIZE | SHGFI_USEFILEATTRIBUTES)
    hIcon, iIcon, dwAttr, name, typeName = info
    ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)
    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x)
    hdc = hdc.CreateCompatibleDC()
    hdc.SelectObject(hbmp)
    hdc.DrawIcon((0, 0), hIcon)
    win32gui.DestroyIcon(hIcon)

    bmpinfo = hbmp.GetInfo()
    bmpstr = hbmp.GetBitmapBits(True)

    img = Image.frombuffer("RGBA", (bmpinfo["bmWidth"], bmpinfo["bmHeight"]),
                           bmpstr, "raw", "BGRA", 0, 1)

    if size == "small":
        img = img.resize((16, 16), Image.ANTIALIAS)

    data = img.tobytes("raw", "RGBA")
    qim = QImage(data, img.size[0], img.size[1], QImage.Format_RGBA8888)

    # qim.save("test.png")

    return qim
예제 #8
0
def take_picture():
    width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
    height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
    left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
    top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

    # Grabs the desktop window handle
    desktophandle = win32gui.GetDesktopWindow()
    windowrect = win32gui.GetClientRect(desktophandle)

    # Create device contexts:
    # A device context is a structure that defines a set of graphic objects
    # and their associated attributes, as well as the graphic modes that affect output.
    desktopcontext = win32gui.GetDC(desktophandle)
    imgdc = win32ui.CreateDCFromHandle(
        desktopcontext)  # This is a PyCDC object, PyCDeviceContext

    # Create memory device context, stores the bitmap until save
    memdc = imgdc.CreateCompatibleDC()

    # Create bitmap object
    screen = win32ui.CreateBitmap()
    screen.CreateCompatibleBitmap(imgdc, width, height)

    # Points the memdc to the newly created bitmap
    memdc.SelectObject(screen)

    # Copy from screen to new bitmap
    memdc.BitBlt((0, 0), (width, height), imgdc, (0, 0), win32con.SRCCOPY)

    # Turn img into a png
    info = screen.GetInfo()
    size = (info['bmWidth'], info['bmHeight'])
    buf = screen.GetBitmapBits(True)
    img = Image.frombuffer('RGB', size, buf, 'raw', 'BGRX', 0, 1)

    # free objects
    memdc.DeleteDC()
    win32gui.DeleteObject(screen.GetHandle())
    return img
예제 #9
0
def grab_screen(region=None):
    logger = log_grab_screen.get_logger('grab_screen')

    while True:
        try:
            hwin = win32gui.GetDesktopWindow()

            if region:
                left, top, x2, y2 = region
                width = x2 - left + 1
                height = y2 - top + 1
            else:
                width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
                height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
                left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
                top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

            hwindc = win32gui.GetWindowDC(hwin)
            srcdc = win32ui.CreateDCFromHandle(hwindc)
            memdc = srcdc.CreateCompatibleDC()
            bmp = win32ui.CreateBitmap()
            bmp.CreateCompatibleBitmap(srcdc, width, height)
            memdc.SelectObject(bmp)
            memdc.BitBlt((0, 0), (width, height), srcdc, (left, top),
                         win32con.SRCCOPY)

            signedIntsArray = bmp.GetBitmapBits(True)
            img = np.fromstring(signedIntsArray, dtype='uint8')
            img.shape = (height, width, 4)

            srcdc.DeleteDC()
            memdc.DeleteDC()
            win32gui.ReleaseDC(hwin, hwindc)
            win32gui.DeleteObject(bmp.GetHandle())

            return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)

        except Exception as e:
            # grab_screen(region)
            logger.error(e)
예제 #10
0
def cap():
    global datime
    hdesktop = win32gui.GetDesktopWindow()
    width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
    height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
    left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
    top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
    desktop_dc = win32gui.GetWindowDC(hdesktop)
    img_dc = win32ui.CreateDCFromHandle(desktop_dc)
    mem_dc = img_dc.CreateCompatibleDC()
    screenshot = win32ui.CreateBitmap()
    screenshot.CreateCompatibleBitmap(img_dc, width, height)
    mem_dc.SelectObject(screenshot)
    mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top),
                  win32con.SRCCOPY)
    Timey()
    new_str = datime.replace(':', '-')
    new_strb = new_str
    location = 'c:\\0\\temp\\screenshot'
    location = location + new_str
    location = location + ".bmp"
    screenshot.SaveBitmapFile(mem_dc, location)
    mem_dc.DeleteDC()
    win32gui.DeleteObject(screenshot.GetHandle())

    ##ftp the cap
    dog = "dog2.bmp"
    new_str2 = "screenshot"
    new_str2 += new_strb
    new_str2 += ".bmp"
    tempstr = "temp\\"
    tempstr += new_str2
    file = open(tempstr, 'rb')
    stor_str = "STOR "
    stor_str += new_str2
    session.storbinary(stor_str, file)
    file.close()
    #session.quit()
    ##delete the file
    os.remove(tempstr)
예제 #11
0
def grab_frame(size=None):

    hwin = win32gui.GetDesktopWindow()

    if size:
        left, top, x, y  = size
        width= x - left + 1
        height= y - top +1

    else:
        width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
        height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
        left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
        top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)



    hwindc = win32gui.GetWindowDC(hwin)
    srcdc = win32ui.CreateDCFromHandle(hwindc)
    memdc = srcdc.CreateCompatibleDC()
    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(srcdc, width, height)
    memdc.SelectObject(bmp)
    memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)


    signedIntsArray = bmp.GetBitmapBits(True)

    img = np.fromstring(signedIntsArray, dtype='uint8')

    img.shape = (height, width, 4)

    srcdc.DeleteDC()
    memdc.DeleteDC()
    win32gui.ReleaseDC(hwin, hwindc)
    win32gui.DeleteObject(bmp.GetHandle())

    img_res = cv2.resize(img, (480,270))
    img_rgb = cv2.cvtColor(img_res, cv2.COLOR_BGRA2RGB)
    return img_rgb
예제 #12
0
    def capture(self, relative=(0, 0)):
        """
        Return a PIL image of the control.

        See PIL documentation to know what you can do with the resulting
        image.
        """
        left, top, right, bot = win32gui.GetWindowRect(self.handle)
        w = right - left
        h = bot - top

        hwndDC = win32gui.GetWindowDC(self.handle)
        mfcDC = win32ui.CreateDCFromHandle(hwndDC)
        saveDC = mfcDC.CreateCompatibleDC()

        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(mfcDC, w + relative[0],
                                          h + relative[1])

        saveDC.SelectObject(saveBitMap)
        saveDC.BitBlt(relative, (w, h), mfcDC, (left, top), win32con.SRCCOPY)

        bmpinfo = saveBitMap.GetInfo()
        bmpstr = saveBitMap.GetBitmapBits(True)
        img = Image.frombuffer('RGB',
                               (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
                               bmpstr, 'raw', 'BGRX', 0, 1)
        """img_w, img_h = img.size
        #font = ImageFont.truetype('Operator Mono Lig.ttf', 20)
        font = ImageFont.truetype('arial.ttf', 100)
        mask = font.getmask('This is watermark text', mode='L')
        mask_w, mask_h = mask.size
        d = Image.core.draw(img.im, 0)
        d.draw_bitmap(((img_w - mask_w)/2, (img_h - mask_h)/2), mask, 100)"""

        win32gui.DeleteObject(saveBitMap.GetHandle())
        saveDC.DeleteDC()
        mfcDC.DeleteDC()
        win32gui.ReleaseDC(self.handle, hwndDC)
        return img
예제 #13
0
def window_capture(windowName='Andor'):
    """
    using native windows api to get capture
    It's the fastest, about ~ms per screenshot   
    """
    (win_num, win_title) = getWindow(windowName)
    # 根据窗口句柄获取窗口的设备上下文DC(Divice Context)
    hwndDC = win32gui.GetWindowDC(win_num)
    # 根据窗口的DC获取mfcDC
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # mfcDC创建可兼容的DC
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建bigmap准备保存图片
    saveBitMap = win32ui.CreateBitmap()

    # get physical monitor information
    """
    MoniterDev = win32api.EnumDisplayMonitors(None, None)
    w = MoniterDev[0][2][2]
    h = MoniterDev[0][2][3]
    """

    # but sometimes there is scaled in the real resolution
    # there it's more important to get actual resolution

    w = int(win32api.GetSystemMetrics(0) / 2)
    h = win32api.GetSystemMetrics(1)
    # print w,h   #图片大小
    # 为bitmap开辟空间
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    # 高度saveDC,将截图保存到saveBitmap中
    saveDC.SelectObject(saveBitMap)
    # 截取从左上角(0,0)长宽为(w,h)的图片
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    # saveBitMap.SaveBitmapFile(saveDC, filename)

    # ! Using fromstring is much faster then normal method
    img = np.fromstring(saveBitMap.GetBitmapBits(True), dtype=np.uint8)
    img = img.reshape((h, w, -1))
    return cv2.cvtColor(img, cv2.COLOR_RGBA2GRAY)
예제 #14
0
 def window_part_shot(self, pos1, pos2, file_name=None, gray=0):
     """
     窗口区域截图
         :param pos1: (x,y) 截图区域的左上角坐标
         :param pos2: (x,y) 截图区域的右下角坐标
         :param file_name=None: 截图文件的保存路径
         :param gray=0: 是否返回灰度图像,0:返回BGR彩色图像,其他:返回灰度黑白图像
         :return: file_name为空则返回RGB数据
     """
     w = pos2[0] - pos1[0]
     h = pos2[1] - pos1[1]
     hwindc = win32gui.GetWindowDC(self.hwnd)
     srcdc = win32ui.CreateDCFromHandle(hwindc)
     memdc = srcdc.CreateCompatibleDC()
     bmp = win32ui.CreateBitmap()
     bmp.CreateCompatibleBitmap(srcdc, w, h)
     memdc.SelectObject(bmp)
     memdc.BitBlt((0, 0), (w, h), srcdc, (pos1[0] + 8, pos1[1] + 31),
                  win32con.SRCCOPY)
     if file_name != None:
         bmp.SaveBitmapFile(memdc, file_name)
         srcdc.DeleteDC()
         memdc.DeleteDC()
         win32gui.ReleaseDC(self.hwnd, hwindc)
         win32gui.DeleteObject(bmp.GetHandle())
         return
     else:
         signedIntsArray = bmp.GetBitmapBits(True)
         img = np.fromstring(signedIntsArray, dtype='uint8')
         img.shape = (h, w, 4)
         srcdc.DeleteDC()
         memdc.DeleteDC()
         win32gui.ReleaseDC(self.hwnd, hwindc)
         win32gui.DeleteObject(bmp.GetHandle())
         #cv2.imshow("image", cv2.cvtColor(img, cv2.COLOR_BGRA2BGR))
         # cv2.waitKey(0)
         if gray == 0:
             return cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
         else:
             return cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
예제 #15
0
    def capture_screenshot(self):
        im = None

        if self.mode == Mode.Window:
            left, top, right, bot = win32gui.GetClientRect(self.hwnd)
            w = right - left
            h = bot - top

            hwnddc = win32gui.GetWindowDC(self.hwnd)
            mfcdc = win32ui.CreateDCFromHandle(hwnddc)
            savedc = mfcdc.CreateCompatibleDC()

            savebitmap = win32ui.CreateBitmap()
            savebitmap.CreateCompatibleBitmap(mfcdc, w, h)

            savedc.SelectObject(savebitmap)

            # Change the line below depending on whether you want the whole window
            # or just the client area.
            result = windll.user32.PrintWindow(self.hwnd, savedc.GetSafeHdc(), 1)
            logging.debug("PrintWindow result: {}".format(result))

            if result == 1:
                bmpinfo = savebitmap.GetInfo()
                logging.debug(bmpinfo)
                bmpstr = savebitmap.GetBitmapBits(True)

                im = Image.frombuffer(
                    'RGB',
                    (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
                    bmpstr, 'raw', 'BGRX', 0, 1)

            win32gui.DeleteObject(savebitmap.GetHandle())
            savedc.DeleteDC()
            mfcdc.DeleteDC()
            win32gui.ReleaseDC(self.hwnd, hwnddc)
        else:
            im = ImageGrab.grab()

        return im
예제 #16
0
파일: Screenshot.py 프로젝트: sch33n/roc
    def shot(cls,name= 'playing.png'):
        hwnd = win32gui.FindWindow(None, cls.processname)

        # Change the line below depending on whether you want the whole window
        # or just the client area. 
        left, top, right, bot = win32gui.GetClientRect(hwnd)
        #left, top, right, bot = win32gui.GetWindowRect(hwnd)
        w = right - left
        h = bot - top

        hwndDC = win32gui.GetWindowDC(hwnd)
        mfcDC  = win32ui.CreateDCFromHandle(hwndDC)
        saveDC = mfcDC.CreateCompatibleDC()

        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)

        saveDC.SelectObject(saveBitMap)

        # Change the line below depending on whether you want the whole window
        # or just the client area. 
        #result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)
        result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)

        bmpinfo = saveBitMap.GetInfo()
        bmpstr = saveBitMap.GetBitmapBits(True)

        im = Image.frombuffer(
            'RGB',
            (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
            bmpstr, 'raw', 'BGRX', 0, 1)

        win32gui.DeleteObject(saveBitMap.GetHandle())
        saveDC.DeleteDC()
        mfcDC.DeleteDC()
        win32gui.ReleaseDC(hwnd, hwndDC)

        if result == 1:
            #PrintWindow Succeeded
            im.save("playing.png")
예제 #17
0
def screen_dump(ofile=os.path.join(DirPath,
                                   time.strftime('%Y%m%d%H%M%S') + '.bmp')):
    try:
        # 获取桌面
        hdesktop = win32gui.GetDesktopWindow()

        # 分辨率适应
        width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
        height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
        left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
        top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

        # 创建设备描述表
        desktop_dc = win32gui.GetWindowDC(hdesktop)
        img_dc = win32ui.CreateDCFromHandle(desktop_dc)

        # 创建一个内存设备描述表
        mem_dc = img_dc.CreateCompatibleDC()

        # 创建位图对象
        screenshot = win32ui.CreateBitmap()
        screenshot.CreateCompatibleBitmap(img_dc, width, height)
        mem_dc.SelectObject(screenshot)

        # 截图至内存设备描述表
        mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top),
                      win32con.SRCCOPY)

        # 将截图保存到文件中
        screenshot.SaveBitmapFile(mem_dc, ofile)

        # 内存释放
        mem_dc.DeleteDC()
        win32gui.DeleteObject(screenshot.GetHandle())
    except Exception, e:
        msg = "[%s]Error:%s\n%s" % (time.ctime(), e.message,
                                    traceback.format_exc())
        with open(LogFile, 'a') as f:
            f.write(msg)
예제 #18
0
    def grab_screen(self, handle=None, width=None, height=None):
        """
        对指定窗口截屏
        :param handle: 需要截屏的窗口句柄
        :param width: 窗口的宽度
        :param height: 窗口的高度
        :return: 截取屏幕的灰度图像
        """
        # 获取窗口DC
        hdDC = win32gui.GetDC(handle)
        # 根据句柄创建一个DC
        newhdDC = win32ui.CreateDCFromHandle(hdDC)
        # 创建一个兼容设备内存的DC
        saveDC = newhdDC.CreateCompatibleDC()
        # 创建bitmap保存图片
        saveBitmap = win32ui.CreateBitmap()

        if width is None and height is None:
            # 获取窗口的位置信息
            left, top, right, bottom = win32gui.GetWindowRect(handle)
            # 窗口长宽
            width = right - left
            height = bottom - top
        # bitmap初始化
        saveBitmap.CreateCompatibleBitmap(newhdDC, width, height)
        saveDC.SelectObject(saveBitmap)
        saveDC.BitBlt((0, 0), (width, height), newhdDC, (0, 0),
                      win32con.SRCCOPY)

        signedIntsArray = saveBitmap.GetBitmapBits(True)
        img = np.frombuffer(signedIntsArray, dtype='uint8')
        img.shape = (height, width, 4)

        newhdDC.DeleteDC()
        saveDC.DeleteDC()
        win32gui.ReleaseDC(handle, hdDC)
        win32gui.DeleteObject(saveBitmap.GetHandle())

        return cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
예제 #19
0
def take_screenshot(x0, y0, dx, dy):
    """
    Takes a screenshot of the region of the active window starting from
    (x0, y0) with width dx and height dy.
    """

    hwnd = win32gui.GetForegroundWindow()   # Window handle
    wDC = win32gui.GetWindowDC(hwnd)        # Window device context
    dcObj = win32ui.CreateDCFromHandle(wDC)
    cDC = dcObj.CreateCompatibleDC()

    dataBitMap = win32ui.CreateBitmap()     # PyHandle object
    dataBitMap.CreateCompatibleBitmap(dcObj, dx, dy)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0,0),(dx, dy) , dcObj, (x0, y0), win32con.SRCCOPY)
    image = dataBitMap.GetBitmapBits(1)

    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, wDC)

    return Image.frombuffer("RGBA", (384, 448), image, "raw", "RGBA", 0, 1)
예제 #20
0
def get_screen(region=None):

    hwin = win32gui.GetDesktopWindow()
    left, top, x2, y2 = region
    width = x2 - left + 1
    height = y2 - top + 1
    hwindc = win32gui.GetWindowDC(hwin)
    srcdc = win32ui.CreateDCFromHandle(hwindc)
    memdc = srcdc.CreateCompatibleDC()
    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(srcdc, width, height)
    memdc.SelectObject(bmp)
    memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
    signedIntsArray = bmp.GetBitmapBits(True)
    img = np.fromstring(signedIntsArray, dtype='uint8')
    img.shape = (height, width, 4)
    srcdc.DeleteDC()
    memdc.DeleteDC()
    win32gui.ReleaseDC(hwin, hwindc)
    win32gui.DeleteObject(bmp.GetHandle())

    return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
예제 #21
0
    def renderText(self, text):
        """render text to a PIL image using the windows API."""
        self.drawDC.SetTextColor(RGB(255, 0, 0))

        # create the compatible bitmap:
        w, h = self.drawDC.GetTextExtent(text)

        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(self.mfcDC, w, h)
        self.drawDC.SelectObject(saveBitMap)

        # draw it
        self.drawDC.DrawText(text, (0, 0, w, h), win32con.DT_LEFT)

        # convert to PIL image
        im = native_bmp_to_pil(self.drawDC.GetSafeHdc(),
                               saveBitMap.GetHandle(), w, h)

        # clean-up
        win32gui.DeleteObject(saveBitMap.GetHandle())

        return im
예제 #22
0
    def frame(self):
        # First get the rect enclosing the window
        left, top, right, bot = win32gui.GetWindowRect(self.window_handle)
        width = right - left
        height = bot - top

        # Now create the bitmap to hold the image
        save_bit_map = win32ui.CreateBitmap()
        save_bit_map.CreateCompatibleBitmap(self.mfcdc, width, height)

        # Print the window
        self.dc.SelectObject(save_bit_map)
        ctypes.windll.user32.PrintWindow(self.window_handle, self.dc.GetSafeHdc(), 0)

        bmpinfo = save_bit_map.GetInfo()
        bmpstr = save_bit_map.GetBitmapBits(True)

        win32gui.DeleteObject(save_bit_map.GetHandle())
        return Image.frombuffer(
            'RGB',
            (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
            bmpstr, 'raw', 'BGRX', 0, 1)
예제 #23
0
def capture_screen(hwnd, w, h):
    # https://stackoverflow.com/questions/19695214/python-screenshot-of-inactive-window-printwindow-win32gui
    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
    saveBitMap = win32ui.CreateBitmap()
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    saveDC.SelectObject(saveBitMap)
    result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)
    bmpinfo = saveBitMap.GetInfo()
    bmpstr = saveBitMap.GetBitmapBits(True)
    im = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
                          bmpstr, 'raw', 'BGRX', 0, 1)

    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)

    if result == 1:
        return im
    return None
예제 #24
0
 def window_full_shot(self, file_name=None, gray=0):
     """
     窗口截图
         :param file_name=None: 截图文件的保存名称
         :param gray=0: 是否返回灰度图像,0:返回BGR彩色图像,其他:返回灰度黑白图像
         :return: file_name为空则返回RGB数据
     """
     try:
         hwindc = win32gui.GetWindowDC(self.hwnd)
         srcdc = win32ui.CreateDCFromHandle(hwindc)
         memdc = srcdc.CreateCompatibleDC()
         bmp = win32ui.CreateBitmap()
         bmp.CreateCompatibleBitmap(srcdc, self._client_w, self._client_h)
         memdc.SelectObject(bmp)
         memdc.BitBlt((0, 0), (self._client_w, self._client_h), srcdc,
                      (self._border_l, self._border_t), win32con.SRCCOPY)
         if file_name != None:
             bmp.SaveBitmapFile(memdc, file_name)
             srcdc.DeleteDC()
             memdc.DeleteDC()
             win32gui.ReleaseDC(self.hwnd, hwindc)
             win32gui.DeleteObject(bmp.GetHandle())
             return
         else:
             signedIntsArray = bmp.GetBitmapBits(True)
             img = np.fromstring(signedIntsArray, dtype='uint8')
             img.shape = (self._client_h, self._client_w, 4)
             srcdc.DeleteDC()
             memdc.DeleteDC()
             win32gui.ReleaseDC(self.hwnd, hwindc)
             win32gui.DeleteObject(bmp.GetHandle())
             #cv2.imshow("image", cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY))
             # cv2.waitKey(0)
             if gray == 0:
                 return cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
             else:
                 return cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
     except:
         pass
예제 #25
0
    def findImage(self, source):
        hdc = win32gui.GetWindowDC(self.hwnd)
        dc_obj = win32ui.CreateDCFromHandle(hdc)
        memorydc = dc_obj.CreateCompatibleDC()
        data_bitmap = win32ui.CreateBitmap()
        data_bitmap.CreateCompatibleBitmap(dc_obj, self.width, self.height)

        memorydc.SelectObject(data_bitmap)
        memorydc.BitBlt((0, 0), (self.width, self.height), dc_obj, (self.dx, self.dy), win32con.SRCCOPY)

        bmpheader = struct.pack("LHHHH", struct.calcsize("LHHHH"),
                                self.width, self.height, 1, 24)
        c_bmpheader = ctypes.create_string_buffer(bmpheader)

        # padded_length = (string_length + 3) & -3 for 4-byte aligned.
        c_bits = ctypes.create_string_buffer(" " * (self.width * ((self.height * 3 + 3) & -3)))

        res = ctypes.windll.gdi32.GetDIBits(memorydc.GetSafeHdc(), data_bitmap.GetHandle(),
                                            0, self.height, c_bits, c_bmpheader, win32con.DIB_RGB_COLORS)

        win32gui.DeleteDC(hdc)
        win32gui.ReleaseDC(self.hwnd, hdc)
        memorydc.DeleteDC()
        win32gui.DeleteObject(data_bitmap.GetHandle())

        cv_im = cv.CreateImageHeader((self.width, self.height), cv.IPL_DEPTH_8U, 3)
        cv.SetData(cv_im, c_bits.raw)
        # flip around x-axis
        cv.Flip(cv_im, None, 0)

        template_source = cv.LoadImage(source)

        # From the manual of MatchTemplate
        result_width = cv_im.width - template_source.width + 1
        result_height = cv_im.height - template_source.height + 1;
        result = cv.CreateImage((result_width, result_height), 32, 1)

        cv.MatchTemplate(cv_im, template_source, result, cv2.TM_CCOEFF_NORMED)
        return cv.MinMaxLoc(result)
예제 #26
0
def window_capture(filename):
    hwnd = 0  # 窗口的編號,0號表示當前活躍窗口
    # 根據窗口句柄獲取窗口的設備上下文DC(Divice Context)
    hwndDC = win32gui.GetWindowDC(hwnd)
    # 根據窗口的DC獲取mfcDC
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # mfcDC創建可兼容的DC
    saveDC = mfcDC.CreateCompatibleDC()
    # 創建bigmap準備保存圖片
    saveBitMap = win32ui.CreateBitmap()
    # 獲取監控器信息
    MoniterDev = win32api.EnumDisplayMonitors(None, None)
    w = MoniterDev[0][2][2]
    h = MoniterDev[0][2][3]
    # print w,h   #圖片大小
    # 為bitmap開闢空間
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    # 高度saveDC,將截圖保存到saveBitmap中
    saveDC.SelectObject(saveBitMap)
    # 截取從左上角(0,0)長寬為(w,h)的圖片
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename)
예제 #27
0
def window_capture(filename):
    hwnd = 0 # 窗口的编号,0号表示当前活跃窗口
    # 根据窗口句柄获取窗口的设备上下文DC(Divice Context)
    hwndDC = win32gui.GetWindowDC(hwnd)
    # 根据窗口的DC获取mfcDC
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # mfcDC创建可兼容的DC
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建bigmap准备保存图片
    saveBitMap = win32ui.CreateBitmap()
    # 获取监控器信息
    MoniterDev = win32api.EnumDisplayMonitors(None, None)
    w = MoniterDev[0][2][2]
    h = MoniterDev[0][2][3]
    # print w,h   #图片大小
    # 为bitmap开辟空间
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    # 高度saveDC,将截图保存到saveBitmap中
    saveDC.SelectObject(saveBitMap)
    # 截取从左上角(0,0)长宽为(w,h)的图片
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename)
예제 #28
0
def wtt(filename, wmin, hmin, wmax, hmax, scaling_factor=1.0):
    wmax = int(wmax * scaling_factor)
    wmin = int(wmin * scaling_factor)
    hmax = int(hmax * scaling_factor)
    hmin = int(hmin * scaling_factor)

    hwnd = 0
    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
    BitMap = win32ui.CreateBitmap()
    # MoniterDev = win32api.EnumDisplayMonitors(None, None)
    BitMap.CreateCompatibleBitmap(mfcDC, wmax - wmin, hmax - hmin)
    saveDC.SelectObject(BitMap)
    saveDC.BitBlt((0, 0), (wmax, hmax), mfcDC, (wmin, hmin), win32con.SRCCOPY)
    BitMap.SaveBitmapFile(saveDC, filename)

    win32gui.DeleteObject(BitMap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)
    cancel_top_most()
예제 #29
0
파일: capture.py 프로젝트: nnnlife/auto2
    def capture(self, x, y):
        dataBitMap = win32ui.CreateBitmap()
        w_handle_DC = win32gui.GetWindowDC(hwnd)
        windowDC = win32ui.CreateDCFromHandle(w_handle_DC)
        memDC = windowDC.CreateCompatibleDC()
        dataBitMap.CreateCompatibleBitmap(windowDC, self.window_width,
                                          self.window_height)
        memDC.SelectObject(dataBitMap)
        memDC.BitBlt((0, 0), (self.window_width, self.window_height), windowDC,
                     (x, y), win32con.SRCCOPY)
        bmpinfo = dataBitMap.GetInfo()
        bmpstr = dataBitMap.GetBitmapBits(True)
        im = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
                              bmpstr, 'raw', 'BGRX', 0, 1)

        windowDC.DeleteDC()
        memDC.DeleteDC()
        win32gui.ReleaseDC(hwnd, w_handle_DC)
        win32gui.DeleteObject(dataBitMap.GetHandle())
        # print("Took ", (datetime.datetime.now() - self.capture_time).total_seconds(), " s")
        self.capture_time = datetime.datetime.now()
        return im
예제 #30
0
    def getContent(self):
        self.getGeometry()
        hwindc = win32gui.GetWindowDC(self.handle)

        srcdc = win32ui.CreateDCFromHandle(hwindc)
        memdc = srcdc.CreateCompatibleDC()
        bmp = win32ui.CreateBitmap()
        bmp.CreateCompatibleBitmap(srcdc, self.width, self.height)
        memdc.SelectObject(bmp)
        memdc.BitBlt((0, 0), (self.width, self.height), srcdc, (0, 0),
                     win32con.SRCCOPY)

        # bmp.SaveBitmapFile(memdc, "output.bmp")

        bits = bmp.GetBitmapBits(True)

        srcdc.DeleteDC()
        memdc.DeleteDC()
        win32gui.ReleaseDC(self.handle, hwindc)
        win32gui.DeleteObject(bmp.GetHandle())

        self.pixels = bits