3

I have code that makes a screenshot of the window using winapi. Then I have to save image to disk and load it again from disk to memory PIL. Is there any way at once without saving to disk to pass this bitmap in the PIL.

import win32gui, win32ui, win32con
import Image

win_name='Book'
bmpfilenamename='1.bmp'
hWnd = win32gui.FindWindow(None, win_name)
windowcor = win32gui.GetWindowRect(hWnd)
w=windowcor[2]-windowcor[0]
h=windowcor[3]-windowcor[1]
wDC = win32gui.GetWindowDC(hWnd)
dcObj=win32ui.CreateDCFromHandle(wDC)
cDC=dcObj.CreateCompatibleDC()
dataBitMap = win32ui.CreateBitmap()
dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
cDC.SelectObject(dataBitMap)
cDC.BitBlt((0,0),(w, h) , dcObj, (0,0), win32con.SRCCOPY)
dataBitMap.SaveBitmapFile(cDC, bmpfilenamename)

#dcObj.DeleteDC()
#cDC.DeleteDC()
#win32gui.ReleaseDC(hWnd, wDC)

im=Image.open(bmpfilenamename)
im.load()
Wolf
  • 9,679
  • 7
  • 62
  • 108
Echeg
  • 2,321
  • 2
  • 21
  • 26

2 Answers2

14

Comment out this line:

dataBitMap.SaveBitmapFile(cDC, bmpfilenamename)

and add this instead:

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

[from another SO question ]

Community
  • 1
  • 1
Gerrat
  • 28,863
  • 9
  • 73
  • 101
-1

If you are using PIL why not to use it for screenshoting?
PIL contains ImageGrab module, which can be used like:

import win32gui, win32ui, win32con
import Image
import ImageGrab

win_name='Book'
hWnd = win32gui.FindWindow(None, win_name)
windowcor = win32gui.GetWindowRect(hWnd)

im = ImageGrab.grab(windowcor)

However it will get correct screenshot only if your app is foreground.

Mikhail Churbanov
  • 4,436
  • 1
  • 28
  • 36
  • 1
    I have many monitors. ImageGrab take screenshot ONLY from main monitor. And winapi take screenshot window without focus. You can take a screenshot of the window is not visible due to overlapping. – Echeg Aug 05 '11 at 06:38