Golang实现网页截图和设置成Windows桌面背景

xiaohai 2021-05-27 14:15:59 1994人围观 标签: Go 
简介前面我通过了Python实现了网页截图并设置成Windows桌面背景,感觉Python编译打包非常麻烦,所以就考虑能否用golang进行实现,那么本文就是记录如何实现该功能的。

chromedp包是一种更快,更简单的方法,可以使用无外部依赖关系(即Selenium,PhantomJS等)来驱动支持Go中的Chrome DevTools协议的浏览器 。

1、首先我们需要安装chromedp
go get -u github.com/chromedp/chromedp
2、完整代码实现
package main

import (
    "context"
    "errors"
    "fmt"
    "github.com/chromedp/cdproto/emulation"
    "github.com/chromedp/cdproto/page"
    cdp "github.com/chromedp/chromedp"
    "io/ioutil"
    "log"
    "math"
    "os"
    "syscall"
    "time"
    "unsafe"
)

func main() {
    for {
        changeWallpaper()
        time.Sleep(180 * time.Second) //三分钟执行一次
    }
}

func changeWallpaper() {
    // 创建新的cdp上下文
    ctx, cancel := cdp.NewContext(context.Background())
    defer cancel()

    // 此处以百度官网首页为例
    urlstr := `https://www.baidu.com`
    var buf []byte
    // 获取 png, quality=90
    if err := cdp.Run(ctx, fullScreenshot(urlstr, 90, &buf)); err != nil {
        log.Fatal(err)
    }
    if err := ioutil.WriteFile("windows.jpg", buf, 0644); err != nil {
        log.Fatal(err)
    }
    dir, _ := os.Getwd()
    err := SetWindowsWallpaper(dir + "/windows.jpg")
    if err != nil {
        fmt.Println("设置桌面背景失败: " + err.Error())
        return
    }
}

//设置windows壁纸函数
func SetWindowsWallpaper(imagePath string) error {
    dll := syscall.NewLazyDLL("user32.dll")
    proc := dll.NewProc("SystemParametersInfoW")
    _t, _ := syscall.UTF16PtrFromString(imagePath)
    ret, _, _ := proc.Call(20, 1, uintptr(unsafe.Pointer(_t)), 0x1|0x2)
    if ret != 1 {
        return errors.New("系统调用失败")
    }
    return nil
}

//实现截图的函数
func fullScreenshot(urlstr string, quality int64, res *[]byte) cdp.Tasks {
    return cdp.Tasks{
        cdp.Navigate(urlstr),
        cdp.ActionFunc(func(ctx context.Context) error {
            _, _, contentSize, _, _, _, err := page.GetLayoutMetrics().Do(ctx)
            if err != nil {
                return err
            }
            width, height := int64(math.Ceil(contentSize.Width)), int64(math.Ceil(contentSize.Height))

            err = emulation.SetDeviceMetricsOverride(width, height, 1, false).
                WithScreenOrientation(&emulation.ScreenOrientation{
                    Type:  emulation.OrientationTypePortraitPrimary,
                    Angle: 0,
                }).
                Do(ctx)
            if err != nil {
                return err
            }

            // 获取全屏截图
            *res, err = page.CaptureScreenshot().
                WithQuality(quality).
                WithClip(&page.Viewport{
                    X:      contentSize.X,
                    Y:      contentSize.Y,
                    Width:  contentSize.Width,
                    Height: contentSize.Height,
                    Scale:  1,
                }).Do(ctx)
            if err != nil {
                return err
            }
            return nil
        }),
    }
}
3、编译打包

参考:https://www.hi917.com/detail/53.html

SET CGO_ENABLED=1
SET GOARCH=
SET GOOS=windows
go build -ldflags "-H=windowsgui" example.go //设置成后台运行

参考文档: