go语言实现屏幕截图的示例代码

2022-10-13

屏幕截图在很多地方都可以 用到,本文主要介绍了go语言实现屏幕截图的示例代码,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

目录
  • 借助第三方库
  • 安装
  • 自定义截图 Capture
  • 全屏截图 CaptureDisplay
  • 获取活动显示器数量 NumActiveDisplays
  • 获取指定屏幕显示范围 GetDisplayBounds
  • 获取自定义矩形区域的截图 CaptureRect
  • 演示

借助第三方库

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())

}

到此这篇关于go语言实现屏幕截图的示例代码的文章就介绍到这了,更多相关go语言屏幕截图内容请搜索北冥有鱼以前的文章或继续浏览下面的相关文章希望大家以后多多支持北冥有鱼!

您可能感兴趣的文章:

  • golang快速实现网页截图的方法

《go语言实现屏幕截图的示例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。