2011-01-03 16 views
0

私は、Windowsマシン上のビットマップに画面をキャプチャするための代替ソリューションを探してきました。ctypesを使用してWindowsで画面をキャプチャする

今、私はPILにImageGrabライブラリがあり、おそらくそれが使用されることに気づいています。 しかし、私の検索では、ctypesを使ってgdi32.dll関数にアクセスし、それらを使って画面をキャプチャするソリューションを紹介しました。 私が出会った1つの特定の解決策がありましたが、それはうまくいかず、何が間違っているか把握しようとしています。

ここでは、ソース・コードです:

from ctypes import * 

class Bitmap(Structure): 
    _fields_ = [("bitmapType", c_long), 
       ("width", c_long), 
       ("height", c_long), 
       ("widthBytes", c_long), 
       ("planes", c_short), 
       ("bitsPerPixel", c_short), 
       ("data", POINTER(c_ulong))] 

if __name__ == "__main__": 
    user32 = WinDLL("user32.dll") 
    gdi32 = WinDLL("gdi32.dll") 

    #Constants 
    SM_CXSCREEN = 0 
    SM_CYSCREEN = 1 
    SRCCOPY = 0xCC0020 

    #Capture the Bitmap 
    width = user32.GetSystemMetrics(SM_CXSCREEN) 
    height = user32.GetSystemMetrics(SM_CYSCREEN) 
    screenDC = user32.GetWindowDC(user32.GetDesktopWindow()) 
    captureDC = gdi32.CreateCompatibleDC(screenDC) 
    captureBitmap = gdi32.CreateCompatibleBitmap(screenDC, width, height) 
    gdi32.SelectObject(captureDC, captureBitmap) 
    gdi32.BitBlt(captureDC, 0, 0, width, height, screenDC, 0, 0, SRCCOPY) 

    picture = Bitmap() 
    gdi32.GetObjectA(captureBitmap, 24, byref(picture)) 

が私に、プログラムの最後に、著者はBitmapオブジェクトにビットマップをコピーしようとしているようですが、今すぐ: 1.私は失敗していますgdi32.GetObjectA関数のドキュメントを見つけるために 2. picutre.data内のデータを表示しようとしているとき(私がpicture.data.contentsにアクセスして間違っていないことを願っています)、 "NULLポインターアクセス"という値エラーが発生します。

ここで、このコードスニペットを見つけたページに問題の答えがありましたが、少し曖昧で非常に有益ではありませんでした。答えを読む:

 
You must allocate the integer array for the data pointer of the BITMAP structure. 
GetObject doesn't it for you. 

はgdi32.CreateCompatibleBitmap機能は、既にそのメモリを割り当てるべきではない、とGetObjectがちょうどビットマップ構造のPythonの表現へのポインタをコピーしませんか?

私は本当にここで混乱しています、この問題に光が当てはまると本当に感謝します。 (私はすでにctypesの参照とMSDN GDI32参照と15以上と15個の開いているタブのようにありますが、私はどちらかの固体把握を持っていないとして、私はサークルで回ってるように、私は感じて見て)

答えて

0

GetObjectビットマップ全体を返しません。 GetObject呼び出し後には、picture.dataは実際にはNULLです。ビットマップを読むにはGetDIBitsが必要です。以下は、GetObject文書からの抜粋です。

If hgdiobj is a handle to a bitmap created by calling CreateDIBSection, and the specified buffer is large enough, the GetObject function returns a DIBSECTION structure. In addition, the bmBits member of the BITMAP structure contained within the DIBSECTION will contain a pointer to the bitmap's bit values.

If hgdiobj is a handle to a bitmap created by any other means, GetObject returns only the width, height, and color format information of the bitmap. You can obtain the bitmap's bit values by calling the GetDIBits or GetBitmapBits function.

関連する問題