Capture desktop screenshots in Go

0
1979
Capture desktop screenshots in Go
Capture desktop screenshots in Go

Just another day for a good Go programming tip. In this article, I will show you how to capture desktop screenshots in Go.

To capture desktop screenshots in Go, we will use the screenshot library.

Create a new Go project and add the following dependency:

$ go get -u github.com/kbinani/screenshot

There are few steps to capture the screenshot:

  1. Get/select display.
  2. Get display boundaries.
  3. Capture the selected boundaries into image data
  4. Save image data into an output file.

This is the complete code which demonstrates all those steps:

package main

import (
	"fmt"
	"github.com/kbinani/screenshot"
	"image/png"
	"os"
)

func main() {
	// query number of active displays
	n := screenshot.NumActiveDisplays()

	for i := 0; i < n; i++ {
		// get display boundaries
		bounds := screenshot.GetDisplayBounds(i)

		// capture screenshots into image data
		img, err := screenshot.CaptureRect(bounds)
		if err != nil {
			panic(err)
		}

		// specify saved filename
		fileName := fmt.Sprintf("%d_%dx%d.png", i, bounds.Dx(), bounds.Dy())
		file, _ := os.Create(fileName)
		defer file.Close()

		// encode image data to PNG format and write it to the output file
		png.Encode(file, img)

		fmt.Printf("Display #%d : %v \"%s\"\n", i, bounds, fileName)
	}
}

Build and execute the code, you will see one or more PNG screenshot files generated.

Quick and easy! That’s how you capture desktop screenshots in Go (golang).

Have fun!