go語言實現(xiàn)屏幕截圖的示例代碼
借助第三方庫
https://github.com/kbinani/screenshot
安裝
go get github.com/kbinani/screenshot
方法
詳情查看
https://pkg.go.dev/github.com/vova616/screenshot
自定義截圖 Capture
func Capture(x, y, width, height int) (*image.RGBA, error)
返回指定桌面區(qū)域的屏幕截圖。x,y是起點坐標(biāo), width,height 是圖片的寬和高。
全屏截圖 CaptureDisplay
func CaptureDisplay(displayIndex int) (*image.RGBA, error)
返回全屏截圖。 displayIndex 是顯示編號,默認(rèn)屏幕是0,如果外接多個顯示,則是1,2,3,4 … 。
獲取活動顯示器數(shù)量 NumActiveDisplays
func NumActiveDisplays()int
返回活動的顯示器的數(shù)量。
獲取指定屏幕顯示范圍 GetDisplayBounds
func GetDisplayBounds(displayIndex int) image.Rectangle
GetDisplayBounds返回displayIndex的顯示范圍, 范圍從(0,0) 坐標(biāo)開始,當(dāng)前屏幕分辨率結(jié)束 ,例如:(0,0)-(1920,1080)。
獲取自定義矩形區(qū)域的截圖 CaptureRect
func CaptureRect(rect image.Rectangle) (*image.RGBA, error)
捕獲桌面的指定區(qū)域。跟Capture類似,主要搭配GetDisplayBounds 使用。
參數(shù)是一個矩形,即兩個點,一個最小點,一個最大點
演示
package main import ( ?? ?"fmt" ?? ?"github.com/kbinani/screenshot" ?? ?"image" ?? ?"image/png" ?? ?"os" ) // save *image.RGBA to filePath with PNG format. func save(img *image.RGBA, filePath string) { ?? ?file, err := os.Create(filePath) ?? ?if err != nil { ?? ??? ?panic(err) ?? ?} ?? ?defer file.Close() ?? ?png.Encode(file, img) } func main() { ?? ?//自定義截圖 ?? ?img, err := screenshot.Capture(0, 0, 500, 500) ?? ?if err != nil { ?? ??? ?panic(err) ?? ?} ?? ?save(img, "自定義.png") ?? ?//獲取所有活動屏幕 ?? ?n := screenshot.NumActiveDisplays() ?? ?if n <= 0 { ?? ??? ?panic("沒有發(fā)現(xiàn)活動的顯示器") ?? ?} ?? ?//全屏截取所有活動屏幕 ?? ?if n > 0 { ?? ??? ?for i := 0; i < n; i++ { ?? ??? ??? ?img, err = screenshot.CaptureDisplay(i) ?? ??? ??? ?if err != nil { ?? ??? ??? ??? ?panic(err) ?? ??? ??? ?} ?? ??? ??? ?fileName := fmt.Sprintf("第%d屏幕截圖.png", i) ?? ??? ??? ?save(img, fileName) ?? ??? ?} ?? ?} ?? ?//使用 Rectangle 自定義截圖 ?? ?// 獲取第一個屏幕顯示范圍 ?? ?var new image.Rectangle = image.Rect(0, 0, 600, 700) ?? ?img, err = screenshot.CaptureRect(new) ?? ?if err != nil { ?? ??? ?panic(err) ?? ?} ?? ?save(img, "new.png") ?? ?//使用 GetDisplayBounds獲取指定屏幕顯示范圍,全屏截圖 ?? ?bounds := screenshot.GetDisplayBounds(0) ?? ?img, err = screenshot.CaptureRect(bounds) ?? ?if err != nil { ?? ??? ?panic(err) ?? ?} ?? ?save(img, "all.png") ?? ?//使用Union獲取指定屏幕 矩形最小點和最大點 ?? ?var all image.Rectangle = image.Rect(0, 0, 0, 0) ?? ?bounds1 := screenshot.GetDisplayBounds(0) ?? ?all = bounds1.Union(all) ?? ?fmt.Println(all.Min.X, all.Min.Y, all.Dx(), all.Dy()) }
到此這篇關(guān)于go語言實現(xiàn)屏幕截圖的示例代碼的文章就介紹到這了,更多相關(guān)go語言屏幕截圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go語言循環(huán)遍歷含有中文的字符串的方法小結(jié)
這篇文章主要介紹了Go語言循環(huán)遍歷含有中文的字符串的幾種方法,文章通過代碼示例講解的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴跟著小編一起來看看吧2023-07-07Golang中 import cycle not allowed 問題
這篇文章主要介紹了Golang中 import cycle not allowed 問題的解決方法,問題從描述到解決都非常詳細(xì),需要的小伙伴可以參考一下2022-03-03