屏幕截图(nim学习系列)

 1 #[
 2     https://gist.github.com/treeform/782149b5fc938753feacfca43637aa90    
 3     License: BSD 3-Clause
 4 ]#
 5 import winim, pixie
 6 import winim/inc/windef
 7 
 8 proc takeScreenshot*: Image=
 9   # get size of the main screen
10   var screenRect: windef.Rect
11   GetClientRect GetDesktopWindow(), addr screenRect
12   let
13     x = screenRect.left
14     y = screenRect.top
15     w = (screenRect.right - screenRect.left)
16     h = (screenRect.bottom - screenRect.top)
17 
18   # create an image
19   var image = newImage(w, h)
20 
21   # copy screen data to bitmap
22   var
23     hScreen = GetDC(cast[HWND](nil))
24     hDC = CreateCompatibleDC(hScreen)
25     hBitmap = CreateCompatibleBitmap(hScreen, int32 w, int32 h)
26 
27 
28   discard SelectObject(hDC, hBitmap)
29   discard BitBlt(hDC, 0, 0, int32 w, int32 h, hScreen, int32 x, int32 y, SRCCOPY)
30 
31   # setup bmi structure
32   var mybmi: BITMAPINFO
33   mybmi.bmiHeader.biSize = int32 sizeof(mybmi)
34   mybmi.bmiHeader.biWidth = w
35   mybmi.bmiHeader.biHeight = h
36   mybmi.bmiHeader.biPlanes = 1
37   mybmi.bmiHeader.biBitCount = 32
38   mybmi.bmiHeader.biCompression = BI_RGB
39   mybmi.bmiHeader.biSizeImage = w * h * 4
40 
41   # copy data from bmi structure to the flippy image
42   discard CreateDIBSection(hdc, addr mybmi, DIB_RGB_COLORS, cast[ptr pointer](unsafeAddr image.data[0]), 0, 0)
43   discard GetDIBits(hdc, hBitmap, 0, h, cast[ptr pointer](unsafeAddr image.data[0]), addr mybmi, DIB_RGB_COLORS)
44 
45   # for some reason windows bitmaps are flipped? flip it back
46   image.flipVertical()
47 
48   # for some reason windows uses BGR, convert it to RGB
49   for i in 0 ..< image.height * image.width:
50     swap image.data[i].r, image.data[i].b
51 
52   # delete data [they are not needed anymore]
53   DeleteObject hdc
54   DeleteObject hBitmap
55 
56   #image.writeFile "screenshot.png"
57   image
58   
59 var image = takeScreenshot()  
60 image.writeFile "screenshot2.png"

From: https://www.cnblogs.com/StudyCat/p/16452495.html

posted @ 2022-07-06 20:57  StudyCat  阅读(140)  评论(0编辑  收藏  举报