duangou2028 2015-11-19 18:27
浏览 125
已采纳

将GDI32.dll位图保存到Golang中的磁盘

My first SO question :-) I wish to take a screenshot from Golang by calling into User32.dll and GDI32.dll on a windows machine (project requirement).

I have a handle to the bitmap containing screenshot pixels. However, I don't know how to access its data or how to save it to disk. Anyone know how to map GDI bitmap to Golang []byte and then save as a JPG or PNG?

package main
import "syscall"

var (
    user32            = syscall.NewLazyDLL("user32.dll")
    procGetClientRect = user32.NewProc("GetClientRect")
    // etc...
    gdi32             = syscall.NewLazyDLL("gdi32.dll")
    procCreateDC      = gdi32.NewProc("CreateDC")
    SRCCOPY      uint = 13369376
   //etc...
)

//
// omitted for brevity
//
func TakeDesktopScreenshotViaWinAPI() {

    // these are all calls to user32.dll or gdi32.dll
    hDesktop := GetDesktopWindow()
    desktopRect := GetClientRect(hDesktop)
    width := int(desktopRect.Right - desktopRect.Left)
    height := int(desktopRect.Bottom - desktopRect.Top)

    // create device contexts
    srcDC := GetDC(hDesktop)
    targetDC := CreateCompatibleDC(srcDC)

    // create bitmap to copy to
    hBitmap := CreateCompatibleBitmap(targetDC, width, height)

    // select the bitmap into target DC
    hOldSelection := SelectObject(targetDC, HGDIOBJ(hBitmap))

    //bit block transfer from src to target
    BitBlt(targetDC, 0, 0, width, height, srcDC, 0, 0, SRCCOPY)

   // how to save the  the data in
   // *hBitmap ???

   // restore selection
   SelectObject(targetDC, hOldSelection)

   // clean up
   DeleteDC(HDC(targetDC))
   ReleaseDC(hDesktop, srcDC)
   DeleteObject(HGDIOBJ(hBitmap))
}
  • 写回答

1条回答 默认 最新

  • dongxu1668 2015-11-19 19:55
    关注

    You could just use the screenshot library by vova616, or take a look at the screenshot_windows.go for the required conversion method.

    As per the provided example:

    package main
    
    import (
        "github.com/vova616/screenshot"
        "image/png"
        "os"
    )
    
    func main() {
        img, err := screenshot.CaptureScreen()
        if err != nil {
            panic(err)
        }
        f, err := os.Create("./ss.png")
        if err != nil {
            panic(err)
        }
        err = png.Encode(f, img)
        if err != nil {
            panic(err)
        }
        f.Close()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建