def __init__(self, title): self.RGBCoefficients = np.asarray([0.299, 0.587, 0.114]) self.title = title win32gui.EnumWindows(self.enumHandler, None) self.getDimensions() hDesktop = win32gui.GetDesktopWindow() hDesktopDC = win32gui.GetWindowDC(hDesktop) self.hSrcDC = win32ui.CreateDCFromHandle(hDesktopDC) self.hMemDC = self.hSrcDC.CreateCompatibleDC() self.hBitmap = win32ui.CreateBitmap() self.hBitmap.CreateCompatibleBitmap(self.hSrcDC, self.cWidth, self.cHeight) self.hMemDC.SelectObject(self.hBitmap) self.alive = True self.autoUpdate()
def _save_selection(self): """Save selection region from the original screenshot.""" assert self.filename is not None assert self._selection is not None left, top, right, bottom = self._selection width = right - left height = bottom - top src_dch = win32gui.CreateCompatibleDC(None) src_dc = win32ui.CreateDCFromHandle(src_dch) src_default = src_dc.SelectObject(self._screenshot) assert src_default is not None dst_dch = win32gui.CreateCompatibleDC(None) dst_dc = win32ui.CreateDCFromHandle(dst_dch) dst_bitmap = win32ui.CreateBitmap() dst_bitmap.CreateCompatibleBitmap(src_dc, width, height) dst_default = dst_dc.SelectObject(dst_bitmap) assert dst_default is not None dst_dc.BitBlt((0, 0), (width, height), src_dc, (left, top), win32con.SRCCOPY) dst_bitmap.SaveBitmapFile(dst_dc, self.filename) self.logger.info("Saved selected region as '%s'", self.filename) dst_dc.SelectObject(dst_default) src_dc.SelectObject(src_default) win32gui.DeleteObject(dst_bitmap.GetHandle()) dst_dc.DeleteDC() src_dc.DeleteDC()
def snapshot(): hwnd = 0 hwndDC = win32gui.GetWindowDC(hwnd) mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() MoniterDev = win32api.EnumDisplayMonitors(None, None) w = MoniterDev[0][2][2] h = MoniterDev[0][2][3] saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) saveDC.SelectObject(saveBitMap) saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY) tempfilename = tempfile.gettempdir() + "/" + str(uuid.uuid1()) saveBitMap.SaveBitmapFile(saveDC, tempfilename) return tempfilename
def draw_rectangle(x: int, y: int): dc = win32gui.GetDC(0) dcObj = win32ui.CreateDCFromHandle(dc) red = win32api.RGB(255, 0, 0) # Red # dcObj.SetBkColor(red) hwnd = win32gui.WindowFromPoint((0, 0)) monitor = (0, 0, win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)) while True: if not check: break n = win32gui.GetCursorPos() dcObj.DrawFocusRect((x, y, n[0], n[1])) win32gui.InvalidateRect(hwnd, monitor, True) # Refresh the entire monitor
def saveExecutableIcon(exe, out="tmp/icon.png"): shell = win32com.client.Dispatch("WScript.Shell") ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON) large, small = win32gui.ExtractIconEx(exe, 0) win32gui.DestroyIcon(small[0]) 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), large[0]) hbmp.SaveBitmapFile(hdc, out) img = Image.open(out) img.save(out, 'png')
def OnDrawItem(self, params): lParam = params[3] sdk = win32ui.GetWin32Sdk() hdc = sdk.ParseDrawItemStruct(lParam) dc = win32ui.CreateDCFromHandle(hdc) rct = self.__splash.GetClientRect() try: win32mu.BitBltBmp(dc, self.__bmp, rct) except: print dc, self.__bmp, rct return br = sdk.CreateBrush(win32con.BS_SOLID, 0, 0) dc.FrameRectFromHandle(rct, br) sdk.DeleteObject(br) dc.DeleteDC()
def window_capture(filename, flag=1): beg = time.time() # 屏幕截图,灵活,速度快;缺点是:写法繁琐,不跨平台。 if flag: hWnd = 0 # 窗口的编号,0号表示当前活跃窗口 # 获取后台窗口的句柄,注意后台窗口不能最小化。窗口的类名可以用Visual Studio的SPY++工具获取 # hWnd = win32gui.FindWindow("Chrome_WidgetWin_1", "在线翻译_有道 - Google Chrome") # # 获取监控器信息,全屏幕,包括多屏 # MoniterDev = win32api.EnumDisplayMonitors(None, None) # w = MoniterDev[0][2][2] # h = MoniterDev[0][2][3] # # print w,h #图片大小 # 获取句柄窗口的大小信息 left, top, right, bot = win32gui.GetWindowRect(hWnd) width = right - left height = bot - top # 返回句柄窗口的设备环境,覆盖整个窗口,包括非客户区,标题栏,菜单,边框 hWndDC = win32gui.GetWindowDC(hWnd) # 创建设备描述表 mfcDC = win32ui.CreateDCFromHandle(hWndDC) # 创建内存设备描述表 saveDC = mfcDC.CreateCompatibleDC() # 创建位图对象准备保存图片 saveBitMap = win32ui.CreateBitmap() # 为bitmap开辟存储空间 saveBitMap.CreateCompatibleBitmap(mfcDC, width, height) # 将截图保存到saveBitMap中 saveDC.SelectObject(saveBitMap) # 保存bitmap到内存设备描述表, 截取从左上角(0,0)长宽为(w,h)的图片 saveDC.BitBlt((0, 0), (width, height), mfcDC, (0, 0), win32con.SRCCOPY) # # 如果要截图到打印设备: # # 最后一个int参数:0-保存整个窗口,1-只保存客户区。如果PrintWindow成功函数返回值为1 # result = windll.user32.PrintWindow(hWnd, saveDC.GetSafeHdc(), 0) # print(result) # PrintWindow成功则输出1 saveBitMap.SaveBitmapFile(saveDC, filename) else: # 每抓取一次屏幕需要的时间约为1s,如果图像尺寸小一些效率就会高一些 img = ImageGrab.grab(bbox=(250, 161, 1141, 610)) img = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 3) print(type(img)) end = time.time() print(end - beg)
def getWindow_Img(hwnd): # 將 hwnd 換成 WindowLong s = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, s | win32con.WS_EX_LAYERED) # 判斷視窗是否最小化 show = win32gui.IsIconic(hwnd) # 將視窗圖層屬性改變成透明 # 還原視窗並拉到最前方 # 取消最大小化動畫 # 取得視窗寬高 if show == 1: win32gui.SystemParametersInfo(win32con.SPI_SETANIMATION, 0) win32gui.SetLayeredWindowAttributes(hwnd, 0, 0, win32con.LWA_ALPHA) win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) x, y, width, height = getWindow_W_H(hwnd) # 創造輸出圖層 hwindc = win32gui.GetWindowDC(hwnd) srcdc = win32ui.CreateDCFromHandle(hwindc) memdc = srcdc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() # 取得視窗寬高 x, y, width, height = getWindow_W_H(hwnd) # 如果視窗最小化,則移到Z軸最下方 if show == 1: win32gui.SetWindowPos(hwnd, win32con.HWND_BOTTOM, x, y, width, height, win32con.SWP_NOACTIVATE) # 複製目標圖層,貼上到 bmp bmp.CreateCompatibleBitmap(srcdc, width, height) memdc.SelectObject(bmp) memdc.BitBlt((0, 0), (width, height), srcdc, (8, 3), win32con.SRCCOPY) # 將 bitmap 轉換成 np signedIntsArray = bmp.GetBitmapBits(True) img = np.fromstring(signedIntsArray, dtype='uint8') img.shape = (height, width, 4) #png,具有透明度的 #img. # 釋放device content srcdc.DeleteDC() memdc.DeleteDC() win32gui.ReleaseDC(hwnd, hwindc) win32gui.DeleteObject(bmp.GetHandle()) # 還原目標屬性 if show == 1: win32gui.SetLayeredWindowAttributes(hwnd, 0, 255, win32con.LWA_ALPHA) win32gui.SystemParametersInfo(win32con.SPI_SETANIMATION, 1) # 回傳圖片 #return img return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
def __init__(self, screen_info, screen_id=-1, screen_number=0, rewards=[1,-1], mode='standard'): # window_size = x,y self.keys = np.array(['none', 'left_arrow', 'right_arrow']) self.scale = screen_info.scale self.action_dim = 3 self.application = screen_info.app self.screen_id = screen_id self.screen_number = screen_number self.shell = win32com.client.Dispatch("WScript.Shell") if screen_id == -1: self.game_window = win32gui.FindWindow(None, self.application) else: self.game_window = self.screen_id # self.window_size = screen_info.size self.window_size = [0,0] # self.window_offset = [(self.window_size[0]+10)*self.screen_number,0] # [0, 0] # self.capture_size = [0,0] self.capture_size = np.copy(screen_info.size) self.window_offset = [(self.capture_size[0]+10)*self.screen_number,0] # [0, 0] self.capture_offset = [0,0] self.capture_zoom = screen_info.zoom self.reward_alive = rewards[0] self.reward_terminal = rewards[1] self.mode = mode self.alive = False self.configure() self.get_application_focus() self.hwnd = win32gui.GetDesktopWindow() self.wDC = win32gui.GetWindowDC(self.hwnd) self.dcObj = win32ui.CreateDCFromHandle(self.wDC) self.cDC = self.dcObj.CreateCompatibleDC() self.dataBitMap = win32ui.CreateBitmap() self.dataBitMap.CreateCompatibleBitmap(self.dcObj, self.capture_size[0], self.capture_size[1]) self.cDC.SelectObject(self.dataBitMap) self.curKey = 'enter' self.prevKey = 'enter' self.state_dim = np.copy(self.capture_size) self.state_dim = [self.state_dim[1], self.state_dim[0]] if self.scale != 1: self.state_dim[0] = int(self.state_dim[0]/self.scale) self.state_dim[1] = int(self.state_dim[1]/self.scale) print(self.state_dim)
def findImageEx(self, source, x, y, width, height): 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) im_region = cv.GetSubRect(cv_im, (x, y, width, height)) #cv.SaveImage('aaak.bmp', im_region) template_source = cv.LoadImage(source) # From the manual of MatchTemplate result_width = im_region.width - template_source.width + 1 result_height = im_region.height - template_source.height + 1; result = cv.CreateImage((result_width, result_height), 32, 1) cv.MatchTemplate(im_region, template_source, result, cv2.TM_CCOEFF_NORMED) minVal, maxVal, minLoc, maxLoc = cv.MinMaxLoc(result) #print minVal, maxVal, minLoc, maxLoc minLoc2 = minLoc[0] + x, minLoc[1] + y maxLoc2 = maxLoc[0] + x, maxLoc[1] + y return minVal, maxVal, minLoc2, maxLoc2
def cut_screen_location(self, width, height, x, y, file_path="D:\\dh2\\system\\1.PNG"): try: hwnd = 0 hwndDC = win32gui.GetWindowDC(hwnd) mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() MoniterDev = win32api.EnumDisplayMonitors(None, None) w = MoniterDev[0][2][2] h = MoniterDev[0][2][3] saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) saveDC.SelectObject(saveBitMap) saveDC.BitBlt((0, 0), (width, height), mfcDC, (x, y), win32con.SRCCOPY) saveBitMap.SaveBitmapFile(saveDC, file_path) except: pass
def background_screenshot(hwnd, width, height): wDC = win32gui.GetWindowDC(hwnd) dcObj = win32ui.CreateDCFromHandle(wDC) cDC = dcObj.CreateCompatibleDC() dataBitMap = win32ui.CreateBitmap() dataBitMap.CreateCompatibleBitmap(dcObj, width, height) cDC.SelectObject(dataBitMap) cDC.BitBlt((0, 0), (width, height), dcObj, (0, 0), win32con.SRCCOPY) dataBitMap.SaveBitmapFile(cDC, 'ssmanipulations/screenshot.bmp') img = cv2.imread('ssmanipulations/screenshot.bmp', cv2.COLOR_BGR2GRAY) #cv2.imshow("Screen", img) dcObj.DeleteDC() cDC.DeleteDC() win32gui.ReleaseDC(hwnd, wDC) win32gui.DeleteObject(dataBitMap.GetHandle())
def capture(hwnd): _,_,w,h = win32gui.GetClientRect(hwnd) hdc = win32gui.GetWindowDC(hwnd) dc = win32ui.CreateDCFromHandle(hdc) mdc = dc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(dc, w, h) mdc.SelectObject(bmp) mdc.BitBlt((0,0), (w,h), dc, (0,0), win32con.SRCCOPY) img = np.frombuffer(bmp.GetBitmapBits(True), dtype='uint8') img.shape = (h, w, 4) dc.DeleteDC() mdc.DeleteDC() win32gui.ReleaseDC(hwnd, hdc) win32gui.DeleteObject(bmp.GetHandle()) return img
def screenshot(): """ スクリーンショット撮ってそれを(Pillow.Imageで)返す """ window = win32gui.GetDesktopWindow() window_dc = win32ui.CreateDCFromHandle(win32gui.GetWindowDC(window)) compatible_dc = window_dc.CreateCompatibleDC() real_width = int(GetSystemMetrics(0) * SCREEN_SCALING_FACTOR) real_height = int(GetSystemMetrics(1) * SCREEN_SCALING_FACTOR) print(real_width, real_height) bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(window_dc, real_width, real_height) compatible_dc.SelectObject(bmp) compatible_dc.BitBlt((0, 0), (real_width, real_height), window_dc, (0, 0), win32con.SRCCOPY) img = Image.frombuffer('RGB', (real_width, real_height), bmp.GetBitmapBits(True), 'raw', 'BGRX', 0, 1) return img
def screenshot(name='screenshot'): hdesktop = win32gui.GetDesktopWindow() width, height, left, top = get_dimensions() 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, f'{name}.bmp') mem_dc.DeleteDC() win32gui.DeleteObject(screenshot.GetHandle())
def WindowDraw(self, rect): ''' Draws a rectangle to the window ''' if self.hwnd is None: return #raise Exception("HWND is none. HWND not called or invalid window name provided.") wDC = win32gui.GetWindowDC(self.hwnd) dcObj = win32ui.CreateDCFromHandle(wDC) #Set background mode to transparent #dcObj.SetBkColor(0x12345) #dcObj.SetBkMode(0) dcObj.Rectangle(rect) # Free Resources dcObj.DeleteDC() win32gui.ReleaseDC(self.hwnd, wDC)
def window_capture(filename): #截屏,传入保存文件名,截屏并保存 hwnd = 0 # 窗口的编号,0号表示当前活跃窗口 hwnd_dc = win32gui.GetWindowDC( hwnd) # 根据窗口句柄获取窗口的设备上下文DC(Divice Context) mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc) # 根据窗口的DC获取mfcDC save_dc = mfc_dc.CreateCompatibleDC() # mfcDC创建可兼容的DC save_bit_map = win32ui.CreateBitmap() # 创建bigmap准备保存图片 moniter_dev = win32api.EnumDisplayMonitors(None, None) # 获取监控器信息 w = moniter_dev[0][2][2] h = moniter_dev[0][2][3] # print w,h #图片大小 save_bit_map.CreateCompatibleBitmap(mfc_dc, w, h) # 为bitmap开辟空间 save_dc.SelectObject(save_bit_map) # 高度saveDC,将截图保存到saveBitmap中 save_dc.BitBlt((0, 0), (w, h), mfc_dc, (0, 0), win32con.SRCCOPY) # 截取从左上角(0,0)长宽为(w,h)的图片 save_bit_map.SaveBitmapFile(save_dc, filename)
def screenShot(filename, start_x, start_y, end_x, end_y): hwnd = 0 #Mark for the window, 0 indicates the currently active one. hwndDC = win32gui.GetWindowDC(hwnd) mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(mfcDC, end_x-start_x, end_y-start_y) #Codes above have already made the screenshot, The following codes are #to save it into a file. saveDC.SelectObject(saveBitMap) saveDC.BitBlt((0, 0), (end_x-start_x, end_y-start_x), mfcDC, (start_x, start_y), win32con.SRCCOPY) #cv.imshow('aaa', saveDC) #cv.waitKey(0) #cv.destroyAllWindows() saveBitMap.SaveBitmapFile(saveDC, filename)
def capture_window(self, size_w, size_h): hwnd = self._handle wDC = win32gui.GetWindowDC(hwnd) dcObj = win32ui.CreateDCFromHandle(wDC) cDC = dcObj.CreateCompatibleDC() dataBitMap = win32ui.CreateBitmap() dataBitMap.CreateCompatibleBitmap(dcObj, size_w, size_h) cDC.SelectObject(dataBitMap) cDC.BitBlt((0, 0), (size_w, size_h), dcObj, (0, 0), win32con.SRCCOPY) dataBitMap.SaveBitmapFile(cDC, "c:\\temp\\bla.bmp") # Free Resources dcObj.DeleteDC() cDC.DeleteDC() win32gui.ReleaseDC(hwnd, wDC) win32gui.DeleteObject(dataBitMap.GetHandle())
def capture(path='', wdName=u'阴阳师-网易游戏', handle=None,x0=0,y0=0,w=0,h=0): try: # 获取要截取窗口的句柄 if handle != None: hwnd = handle else: hwnd = win32gui.FindWindow(0, wdName) # 获取句柄窗口的大小信息 # 可以通过修改该位置实现自定义大小截图 if w == 0 or h == 0: 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) # 截图至内存设备描述表 img_dc = mfcDC mem_dc = saveDC mem_dc.BitBlt((0, 0), (w, h), img_dc, (x0, y0), win32con.SRCCOPY) # mem_dc.BitBlt((0,0), (916,116), img_dc, (170, 270), win32con.SRCCOPY) # 将截图保存到文件中 saveBitMap.SaveBitmapFile(mem_dc, path + '/%s.bmp'%hwnd) # 释放内存,不然会造成资源泄漏 win32gui.DeleteObject(saveBitMap.GetHandle()) saveDC.DeleteDC() # png = Image.open(path + '/temp.bmp') # png.save(path + '/temp.png') # return png except Exception as e: print("截图失败,%s,%s"%(e,path))
def getScreenshot(string_input): #http://stackoverflow.com/questions/19695214/python-screenshot-of-inactive-window-printwindow-win32gui hwnd = win32gui.FindWindow(None, string_input) win32gui.MoveWindow(hwnd, 0, 0, 1493, 1058, 0) # 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) #print(result) 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 return im
def liveImageFunction(self): try: if win32gui.GetWindowText(self.hwnd) == '': self.regionError() self.timerLiveImage.stop() return ctypes.windll.user32.SetProcessDPIAware() DwmGetWindowAttribute = ctypes.windll.dwmapi.DwmGetWindowAttribute DWMWA_EXTENDED_FRAME_BOUNDS = 9 rect = ctypes.wintypes.RECT() DwmGetWindowAttribute( self.hwnd, ctypes.wintypes.DWORD(DWMWA_EXTENDED_FRAME_BOUNDS), ctypes.byref(rect), ctypes.sizeof(rect)) self.top = self.y1 - self.top_old self.left = self.x1 - self.left_old wDC = win32gui.GetWindowDC(self.hwnd) dcObj = win32ui.CreateDCFromHandle(wDC) cDC = dcObj.CreateCompatibleDC() bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(dcObj, self.width, self.height) cDC.SelectObject(bmp) cDC.BitBlt((0, 0), (self.width, self.height), dcObj, (self.left, self.top), win32con.SRCCOPY) img = bmp.GetBitmapBits(True) img = np.frombuffer(img, dtype='uint8') img.shape = (self.height, self.width, 4) img = cv2.resize(img, (240, 180)) # Resize to match the label size img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB) # Convert to set it on the label qImg = QtGui.QImage(img, img.shape[1], img.shape[0], img.shape[1] * 3, QtGui.QImage.Format_RGB888) pix = QtGui.QPixmap(qImg) self.liveImage.setPixmap(pix) # Cleanup dcObj.DeleteDC() cDC.DeleteDC() win32gui.ReleaseDC(self.hwnd, wDC) win32gui.DeleteObject(bmp.GetHandle()) except AttributeError: pass
def grab_screen(region=None): 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)
def grab_screen(winName: str = "Grand Theft Auto V"): desktop = win32gui.GetDesktopWindow() # get area by a window name gtawin = win32gui.FindWindow(None, winName) # get the bounding box of the window left, top, x2, y2 = win32gui.GetWindowRect(gtawin) # cut window boarders top += 32 left += 3 y2 -= 4 x2 -= 4 width = x2 - left + 1 height = y2 - top + 1 # the device context(DC) for the entire window (title bar, menus, scroll bars, etc.) hwindc = win32gui.GetWindowDC(desktop) # Create a DC object from an integer handle srcdc = win32ui.CreateDCFromHandle(hwindc) # Create a memory device context that is compatible with the source DC memdc = srcdc.CreateCompatibleDC() # Create a bitmap object bmp = win32ui.CreateBitmap() # Create a bitmap compatible with the specified device context bmp.CreateCompatibleBitmap(srcdc, width, height) # Select an object into the device context. memdc.SelectObject(bmp) # Copy a bitmap from the source device context to this device context # parameters: destPos, size, dc, srcPos, rop(the raster operation)) memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY) # the bitmap bits signedIntsArray = bmp.GetBitmapBits(True) # form a 1-D array initialized from text data in a string. img = np.fromstring(signedIntsArray, dtype='uint8') img.shape = (height, width, 4) # Delete all resources associated with the device context srcdc.DeleteDC() memdc.DeleteDC() # Releases the device context win32gui.ReleaseDC(desktop, hwindc) # Delete the bitmap and freeing all system resources associated with the object. # After the object is deleted, the specified handle is no longer valid. win32gui.DeleteObject(bmp.GetHandle()) return cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
def next_week_planned(): global top_hwnd try: hwnd = win32gui.FindWindow(None, top_hwnd) # 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) #print(result) 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: im.save("./test.jpg") imageobject = Image.open("./test.jpg") cropped = imageobject.crop((245, 170, 1920, 730)) cropped = cropped.resize( (int(cropped.width * .75), int(cropped.height * .75)), Image.ANTIALIAS) cropped.save("./cropped.jpg") os.remove("./test.jpg") except Exception as e: print("\n" + str(e))
def windowFeed(windowName, clientArea=True): # set up hwnd = findWindow(windowName) if clientArea: left, top, right, bot = win32gui.GetClientRect(hwnd) else: 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) # cv2.namedWindow('capure',cv2.WINDOW_NORMAL) # cv2.resizeWindow('capure', 400,300) # main loop while True: oldTime = time.time() if clientArea: result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1) else: result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0) bmpinfo = saveBitMap.GetInfo() bmpstr = saveBitMap.GetBitmapBits(True) img = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'RGBX', 0, 1) if result == 1: cv2.imshow('capure', np.array(img)) pass if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break print("FPS: {:.2f}".format(1 / (time.time() - oldTime))) # clean up win32gui.DeleteObject(saveBitMap.GetHandle()) saveDC.DeleteDC() mfcDC.DeleteDC() win32gui.ReleaseDC(hwnd, hwndDC)
def threadscreenshot(self): dir_exists = os.path.isdir(self.directionname) if not dir_exists: os.mkdir(self.directionname) print("Making directory %s" %self.directionname) else: print("Will store images in directory %s" %self.directionname) while self.screenshot_enable: if self.index%50 == 0: pickle.dump(self.y, open(self.y_dir, 'wb')) print('save y at index =', self.index) time0 = time.time() fn = './' + self.directionname + '/' + str(self.index).zfill(self.zfillnum) + '.bmp' hwnd = win32gui.FindWindow(None, self.windowname) wDC = win32gui.GetWindowDC(hwnd) dcObj=win32ui.CreateDCFromHandle(wDC) cDC=dcObj.CreateCompatibleDC() dataBitMap = win32ui.CreateBitmap() dataBitMap.CreateCompatibleBitmap(dcObj, self.w, self.h) cDC.SelectObject(dataBitMap) cDC.BitBlt((0,0),(self.w, self.h) , dcObj, (0,0), win32con.SRCCOPY) time1 = time.time() #add filter here num = [0, 0] for i in range(self.filter_length): lmr, fmb = self.LeftMiddleRight() num[0] += lmr num[1] += fmb time.sleep(0.00001) num[0] = num[0]/self.filter_length num[1] = num[1]/self.filter_length time2 = time.time() self.index += 1 dataBitMap.SaveBitmapFile(cDC, fn) self.y.append(num) print('save screenshot', fn, ' regression num =', num) # Free Resources dcObj.DeleteDC() cDC.DeleteDC() win32gui.ReleaseDC(hwnd, wDC) win32gui.DeleteObject(dataBitMap.GetHandle()) time3 = time.time() print(time1-time0, time2-time1, time3-time2)
def screenshot(file_name, window_name='Legends of Runeterra'): # https://stackoverflow.com/questions/19695214/python-screenshot-of-inactive-window-printwindow-win32gui import win32gui import win32ui from ctypes import windll from PIL import Image hwnd = win32gui.FindWindow(None, window_name) # 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: logger.info(f'Saving screenshot to {file_name}') im.save(file_name)
def capture_screen(cls, file_path): 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, (0, 0), win32con.SRCCOPY) screenshot.SaveBitmapFile(mem_dc, file_path) mem_dc.DeleteDC() win32gui.DeleteObject(screenshot.GetHandle()) return width, height
def capture_screenshot(): date_string = datetime.datetime.now().strftime("%Y-%m-%dh%Hm%Ms%S") hwin = 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) 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) imgpath = 'screenshots\screenshot'+date_string+'.bmp' print(imgpath) bmp.SaveBitmapFile(memdc, imgpath)