【问题标题】:How to convert HBITMAP to image.ImageHow to convert HBITMAP to image.Image
【发布时间】:2022-12-02 10:37:36
【问题描述】:

I want to retrieve an image from a specific application and convert it to image.Image for later use.

What I have now is a HBITMAP from windows API call. After trying a lots, I can't manage to convert the created HBITMAP to an image.Image (or at least an []byte).

rc := w32.GetClientRect(hwnd)
if rc != nil {
    // create
    HDCScreen := w32.GetWindowDC(hwnd)
    hdc := w32.CreateCompatibleDC(HDCScreen)
    hbmp := w32.CreateCompatibleBitmap(HDCScreen, int(rc.Right)-int(rc.Left), int(rc.Bottom)-int(rc.Top))
    w32.SelectObject(hdc, w32.HGDIOBJ(hbmp))

    // Print to memory hdc
    w32.PrintWindow(hwnd, hdc, 0x00000002)

    // ------------------------------------------------
    var bmpInfo *w32.BITMAPINFO = &w32.BITMAPINFO{}
    bmpInfo.BmiHeader.BiSize = uint32(unsafe.Sizeof(bmpInfo.BmiHeader))

    firstDIBits := w32.GetDIBits(HDCScreen, hbmp, 0, 0, nil, bmpInfo, w32.DIB_RGB_COLORS)
    fmt.Printf("firstDIBits: %v\n", firstDIBits)

    var lpPixels *[]byte
    bmpInfo.BmiHeader.BiBitCount = 32
    bmpInfo.BmiHeader.BiCompression = w32.BI_RGB
    bmpInfo.BmiHeader.BiHeight = int32(math.Abs(float64(bmpInfo.BmiHeader.BiHeight)))
    bmpInfo.BmiHeader.BiCompression = w32.BI_RGB

    secondDIBits := w32.GetDIBits(hdc, hbmp, 0, uint(bmpInfo.BmiHeader.BiHeight), unsafe.Pointer(lpPixels), bmpInfo, w32.DIB_RGB_COLORS)
    fmt.Printf("secondDIBits: %v\n", secondDIBits)
    fmt.Printf("lpPixels: %v\n", lpPixels)

    // ------------------------------------------------

    // copy to clipBoard
    w32.OpenClipboard(0)
    w32.EmptyClipboard()
    w32.SetClipboardData(w32.CF_BITMAP, w32.HANDLE(hbmp))
    w32.CloseClipboard()

    // release
    w32.DeleteDC(hdc)
    w32.DeleteObject(w32.HGDIOBJ(hbmp))
    w32.ReleaseDC(0, HDCScreen)
}

Both of GetDIBits() call return 1 but lpPixels is always nil.

【问题讨论】:

    标签: go winapi data-conversion


    【解决方案1】:

    The Bitmap class inherits from the Image class.In my opinion, you couldn't need the conversion.

    According to the Doc:GetDIBits function

    [out] lpvBits

    A pointer to a buffer to receive the bitmap data. If this parameter is NULL, the function passes the dimensions and format of the bitmap to the BITMAPINFO structure pointed to by the lpbi parameter.

    I don't know much about Go language, but the lpvBits parameter of GetDIBits seem incorrect. I suggest you could refer to the threads:

    Using GetDIBits to load a bitmap

    How should I use the GetDIBits function

    【讨论】:

      猜你喜欢
      • 2022-12-16
      • 2022-12-02
      • 2022-12-26
      • 2022-12-02
      • 2022-12-27
      • 2022-12-28
      • 2022-12-26
      • 2022-11-20
      • 2011-04-06
      相关资源
      最近更新 更多