Golang实现网页截图和设置成Windows桌面背景
简介前面我通过了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 //设置成后台运行
参考文档:
快速生成表格
《康熙王朝》是一部非常优秀的电视连续剧,陈道明演的康熙是我觉得最有帝王气魄,让人意犹未尽,本文主要记录一小段非常经典的对白。
top命令用于实时显示系统中进程占用资源的情况。该命令还可以按照CPU的使用、内存使用和执行时间对系统进程进行排序显示。同时top命令还可以通过交互命令进行设定显示
默认情况下 pip 使用的是国外的镜像,在下载的时候速度非常慢,本文我们介绍使用国内源对pip进行加速。
Electron页面跳转、浏览器打开链接和打开新窗口
Docker编译镜像出现:fetch http://dl-cdn.alpinelinux.org/alpine/v3.12/main/x86_64/APKINDEX.tar.gz
ERROR: http://dl-cdn.alpinelinux.org/alpine/v3.12/main: temporary error (try again later)
WARNING: Ignoring APKINDEX.2c4ac24e.tar.gz: No such file or directory问题
在Mac电脑中,如何对Git的用户名和密码进行修改呢?起初不懂Mac,所以整了很久,本文将记录如何对这个进行操作,以便后期使用。
在使用Git的过程中,不想每次都输入用户名和密码去拉取代码,所以就需要保存这些信息,那么既然有保存了,就必须有清除功能。