【问题标题】:Saving GDI32.dll bitmap to disk in Golang在 Golang 中将 GDI32.dll 位图保存到磁盘
【发布时间】:2016-02-22 01:14:04
【问题描述】:

我的第一个 SO 问题 :-) 我希望通过在 Windows 机器上调用 User32.dll 和 GDI32.dll 从 Golang 截取屏幕截图(项目要求)。

我有一个包含屏幕截图像​​素的位图句柄。但是,我不知道如何访问其数据或如何将其保存到磁盘。有谁知道如何将 GDI 位图映射到 Golang []byte 然后另存为 JPG 或 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))
}

【问题讨论】:

  • image\jpeg 提供了一个从io.Reader 读取的解码器/编码器。我认为如果GDIbitmap 不符合 Reader 接口,那么扩展它并不难。
  • 感谢@miltonb,尝试一下。将恢复我的发现。
  • 最终使用了 vova 库,它干净地返回了 golang 的 rect 结构。

标签: go bitmap gdi


【解决方案1】:

您可以直接使用 vova616 的the screenshot library,或查看screenshot_windows.go 以了解所需的转换方法。

根据提供的示例:

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()
}

【讨论】:

  • 谢谢,在构建 github.com/allendang/w32 依赖项时遇到问题。继续获取 cgo.exe 退出状态 2. 将用我的发现更新这篇文章。
  • 我无法在我的系统上正确构建 w32 依赖项。因此,按照建议,我查看了 _windows.go 实现,获取了我的项目需要的东西,然后一切都像魅力一样工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-10-13
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-21
  • 2016-09-14
相关资源
最近更新 更多