python deletedc_python – 具有16位图像数据的Image.frombuffer

如果我的窗口是32位颜色深度模式,那么下面的代码从窗口获取一个漂亮的PIL图像:

def image_grab_native(window):

hwnd = win32gui.GetDesktopWindow()

left, top, right, bot = get_rect(window)

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)

saveDC.BitBlt((0, 0), (w, h), mfcDC, (left, top), win32con.SRCCOPY)

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)

return im

但是,在16位模式下运行时,我收到错误:

>>> image_grab_native(win)

Traceback (most recent call last):

File "", line 1, in

image_grab_native(win)

File "C:\claudiu\bumhunter\finderbot\ezpoker\utils\win32.py", line 204, in image_grab_native

bmpstr, 'raw', 'BGRX', 0, 1)

File "c:\python25\lib\site-packages\PIL\Image.py", line 1808, in frombuffer

return apply(fromstring, (mode, size, data, decoder_name, args))

File "c:\python25\lib\site-packages\PIL\Image.py", line 1747, in fromstring

im.fromstring(data, decoder_name, args)

File "c:\python25\lib\site-packages\PIL\Image.py", line 575, in fromstring

raise ValueError("not enough image data")

ValueError: not enough image data

我应该如何形成frombuffer调用以在16位模式下工作?另外,如何使此功能在任何位深度模式下工作,而不是说必须将其作为参数传递?

更新:从this question开始我学会了必须使用“BGR; 16”而不是“BGRX”作为第二模式参数.它需要一个正确的图片,无论是否指定步幅.问题是某些值的像素值略有偏差:

x y native ImageGrab

280 0 (213, 210, 205) (214, 211, 206)

280 20 (156, 153, 156) (156, 154, 156)

280 40 (213, 210, 205) (214, 211, 206)

300 0 (213, 210, 205) (214, 211, 206)

只是从同一窗口获取的值的示例.屏幕截图看起来与肉眼完全相同,但我必须做一些像素操作..我想要使用本机方法的原因是它更快一点,并且当在具有双显示器的虚拟机内运行时表现更好. (我知道,这是非常随意的复杂).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值