日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

go語言實現屏幕截圖的示例代碼_Golang

作者:Clown95 ? 更新時間: 2022-06-20 編程語言

借助第三方庫

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)

返回指定桌面區域的屏幕截圖。x,y是起點坐標, width,height 是圖片的寬和高。

全屏截圖 CaptureDisplay

func CaptureDisplay(displayIndex int) (*image.RGBA, error)

返回全屏截圖。 displayIndex 是顯示編號,默認屏幕是0,如果外接多個顯示,則是1,2,3,4 … 。

獲取活動顯示器數量 NumActiveDisplays

func NumActiveDisplays()int

返回活動的顯示器的數量。

獲取指定屏幕顯示范圍 GetDisplayBounds

func GetDisplayBounds(displayIndex int) image.Rectangle

GetDisplayBounds返回displayIndex的顯示范圍, 范圍從(0,0) 坐標開始,當前屏幕分辨率結束 ,例如:(0,0)-(1920,1080)。

獲取自定義矩形區域的截圖 CaptureRect

func CaptureRect(rect image.Rectangle) (*image.RGBA, error)

捕獲桌面的指定區域。跟Capture類似,主要搭配GetDisplayBounds 使用。
參數是一個矩形,即兩個點,一個最小點,一個最大點

演示

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("沒有發現活動的顯示器")
?? ?}

?? ?//全屏截取所有活動屏幕
?? ?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())

}

原文鏈接:https://blog.csdn.net/yang731227/article/details/108176980

欄目分類
最近更新