简体   繁体   中英

How do I capture the screen using Ruby?

I need to capture the screen using Ruby, and then get an array of RGB pixel values for each pixel on the screen.

I tried the Windows API, and can bitblt the screen and retrieve the handle of the bitmap, but I have no idea how to access the raw RGB values within this handle's data.

This is what I have at the moment, and it's fast enough, but I need to get the RGB values from the hbitmap into an array that I can work with.

Anything as fast as Bitblt but easier would be appreciated too.

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

I figured out how to do this so I though I would post the solution for others who may need help.

The GetDIBits Win32API function can be used to access the RGB array stored in the bitmap captured using the above code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM