如何使用Ruby捕获屏幕?

时间:2011-12-30 23:37:26

标签: ruby winapi

我需要使用Ruby捕获屏幕,然后为屏幕上的每个像素获取一个RGB像素值数组。

我尝试了Windows API,可以对屏幕进行bitblt并检索位图的句柄,但我不知道如何访问此句柄数据中的原始RGB值。

这就是我目前所拥有的,而且速度足够快,但我需要将hbitmap中的RGB值转换为可以使用的数组。

任何与Bitblt一样快但更容易的东西也会受到赞赏。

def getscreen()

width = Win32API.new("User32.dll","GetSystemMetrics",["L"],"L").call(0)
height = Win32API.new("User32.dll","GetSystemMetrics",["L"],"L").call(1)

#Get desktop DC, create a compatible dc, create a comaptible bitmap and select into compatible dc.
hddc = Win32API.new("User32.dll","GetDC",["L"],"L").call(Win32API.new("User32.dll","GetDesktopWindow",[],"L").call)
hcdc = Win32API.new("Gdi32.dll","CreateCompatibleDC",["L"],"L").call(hddc)
hbitmap = Win32API.new("Gdi32.dll","CreateCompatibleBitmap",["L","L","L"],"L").call(hddc,width,height)
Win32API.new("Gdi32.dll","SelectObject",["L","L"],"L").call(hcdc,hbitmap)
Win32API.new("Gdi32.dll","BitBlt",["L","L","L","L","L","L","L","L","P"],"L").call(hcdc,0,0,width,height,hddc,0,0,"SRCCOPY|CAPTUREBLT")

#save hbitmap to stream of byte as you mentioned
puts hbitmap


#

Win32API.new("User32.dll","ReleaseDC",["L","L"],"L").call(Win32API.new("User32.dll","GetDesktopWindow",[],"L").call,hddc)
Win32API.new("Gdi32.dll","DeleteDC",["L"],"L").call(hcdc)
Win32API.new("Gdi32.dll","DeleteObject",["L"],"L").call(hbitmap)

#Print screen width and height
puts "Screen width: #{width}"
puts "Screen height: #{height}"

end

1 个答案:

答案 0 :(得分:0)

我想出了如何做到这一点,所以我会为其他可能需要帮助的人发布解决方案。

GetDIBits Win32API函数可用于访问存储在使用上述代码捕获的位图中的RGB数组。

http://msdn.microsoft.com/en-us/library/dd144879%28v=vs.85%29.aspx