go语言屏幕截图

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

go语言屏幕截图

Clown95   2022-06-03 我要评论

借助第三方库

https://github.com/kbinani/screenshot

安装

go get github.com/kbinani/screenshot

方法

详情查看
http://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())

}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们