定义了一个函数 SavePicture(hBM, sFile),用于将内存中的位图(HBITMAP)保存为图片文件(支持多种格式,如 BMP、JPEG、GIF、TIFF、PNG)。它适合开发图像处理工具、截图应用或图片格式转换程序。

 

将 hBitmap 保存为 BMP、JPG、GIF、PNG、TIF.ahk

GDIP("Startup")

hBM := HBitmapFromScreen()

SavePicture(hBM, A_Desktop "\全屏截图.jpg")
Return

; https://www.autohotkey.com/boards/viewtopic.php?f=6&t=67716
SavePicture(hBM, sFile) {
  Local V, pBM := VarSetCapacity(V,16,0)>>8, Ext := LTrim(SubStr(sFile,-3),"."), E := [0,0,0,0]
  Local Enc := 0x557CF400 | Round({"bmp":0, "jpg":1,"jpeg":1,"gif":2,"tif":5,"tiff":5,"png":6}[Ext])
  E[1] := DllCall("gdi32\GetObjectType", "Ptr",hBM ) <> 7
  E[2] := E[1] ? 0 : DllCall("gdiplus\GdipCreateBitmapFromHBITMAP", "Ptr",hBM, "UInt",0, "PtrP",pBM)
  NumPut(0x2EF31EF8,NumPut(0x0000739A,NumPut(0x11D31A04,NumPut(Enc+0,V,"UInt"),"UInt"),"UInt"),"UInt")
  E[3] := pBM ? DllCall("gdiplus\GdipSaveImageToFile", "Ptr",pBM, "WStr",sFile, "Ptr",&V, "UInt",0) : 1
  E[4] := pBM ? DllCall("gdiplus\GdipDisposeImage", "Ptr",pBM) : 1
  Return E[1] ? 0 : E[2] ? -1 : E[3] ? -2 : E[4] ? -3 : 1
}

GDIP(C:="Startup") {
  Static SI:=Chr(!(VarSetCapacity(Si,24,0)>>16)), pToken:= hMod:= Res:= AOK:=0
  if (AOK := (C="Startup" and pToken=0) Or (C<>"Startup" and pToken<>0)) {
    if (C="Startup") {
      hMod := DllCall("LoadLibrary", "Str","gdiplus.dll", "Ptr")
      Res := DllCall("gdiplus\GdiplusStartup", "PtrP", pToken, "Ptr", &SI, "UInt",0)
    } else {
      Res := DllCall("gdiplus\GdiplusShutdown", "Ptr", pToken)
      DllCall("FreeLibrary", "Ptr", hMod), hMod:=0, pToken:=0
    }
  }
  Return (AOK ? !Res : Res:=0)
}


HBitmapFromScreen(X:=0, Y:=0, W:=0, H:=0) {
  (W=0 && W:=A_ScreenWidth), (H=0 && H:=A_ScreenHeight)
  , HDC := DllCall("GetDC", "Ptr", 0, "UPtr")
  , hBM := DllCall("CreateCompatibleBitmap", "Ptr", HDC, "Int", W, "Int", H, "UPtr")
  , PDC := DllCall("CreateCompatibleDC", "Ptr", HDC, "UPtr")
  , DllCall("SelectObject", "Ptr", PDC, "Ptr", hBM)
  , DllCall("BitBlt", "Ptr", PDC, "Int", 0, "Int", 0, "Int", W, "Int", H
      , "Ptr", HDC, "Int", X, "Int", Y, "UInt", 0x00CC0020)
  , DllCall("DeleteDC", "Ptr", PDC)
  , DllCall("ReleaseDC", "Ptr", 0, "Ptr", HDC)
  Return hBM
}

 

 

声明:站内资源为整理优化好的代码上传分享与学习研究,如果是开源代码基本都会标明出处,方便大家扩展学习路径。请不要恶意搬运,破坏站长辛苦整理维护的劳动成果。本站为爱好者分享站点,所有内容不作为商业行为。如若本站上传内容侵犯了原著者的合法权益,请联系我们进行删除下架。