Module screenBitmap
[hide private]
[frames] | no frames]

Source Code for Module screenBitmap

 1  import ctypes 
 2  import winGDI 
 3   
 4  user32=ctypes.windll.user32 
 5  gdi32=ctypes.windll.gdi32 
 6   
7 -class ScreenBitmap(object):
8 """Provides a way to capture a bitmap of any part of the screen. The object caches needed DCs and bitmaps therefore an instance of an object only handles one size of bitmap.""" 9
10 - def __init__(self,width,height):
11 """ 12 @param width: the width of the resulting bitmap in rgb pixels. 13 @param height: the height of the bitmap in rgb pixels. 14 """ 15 self.width=width 16 self.height=height 17 #Fetch the device context for the screen 18 self._screenDC=user32.GetDC(0) 19 #Create a memory device context with which we can copy screen content to on request. 20 self._memDC=gdi32.CreateCompatibleDC(self._screenDC) 21 #Create a new bitmap of the chosen size, and set this as the memory device context's bitmap, so that what is drawn is captured. 22 self._memBitmap=gdi32.CreateCompatibleBitmap(self._screenDC,width,height) 23 self._oldBitmap=gdi32.SelectObject(self._memDC,self._memBitmap) 24 #We always want standard RGB data 25 bmInfo=winGDI.BITMAPINFO() 26 bmInfo.bmiHeader.biSize=ctypes.sizeof(bmInfo) 27 bmInfo.bmiHeader.biWidth=width 28 bmInfo.bmiHeader.biHeight=height*-1 29 bmInfo.bmiHeader.biPlanes=1 30 bmInfo.bmiHeader.biBitCount=32 31 bmInfo.bmiHeader.biCompression=winGDI.BI_RGB 32 self._bmInfo=bmInfo
33
34 - def __del__(self):
35 gdi32.SelectObject(self._memDC,self._oldBitmap) 36 gdi32.DeleteObject(self._memBitmap) 37 gdi32.DeleteDC(self._memDC) 38 user32.ReleaseDC(0,self._screenDC)
39
40 - def captureImage(self,x,y,w,h):
41 """ 42 Captures the part of the screen starting at x,y and extends by w (width) and h (height), and stretches/shrinks it to fit in to the object's bitmap size. 43 """ 44 #Copy the requested content from the screen in to our memory device context, stretching/shrinking its size to fit. 45 gdi32.StretchBlt(self._memDC,0,0,self.width,self.height,self._screenDC,x,y,w,h,winGDI.SRCCOPY) 46 #Fetch the pixels from our memory bitmap and store them in a buffer to be returned 47 buffer=(winGDI.RGBQUAD*w*h)() 48 gdi32.GetDIBits(self._memDC,self._memBitmap,0,self.height,buffer,ctypes.byref(self._bmInfo),winGDI.DIB_RGB_COLORS); 49 return buffer
50
51 -def rgbPixelBrightness(p):
52 """Converts a RGBQUAD pixel in to one grey-scale brightness value.""" 53 return int((0.3*p.rgbBlue)+(0.59*p.rgbGreen)+(0.11*p.rgbRed))
54