Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a local desktop screenshot in Go, use github.com/kbinani/screenshot: enumerate active displays, get a display’s bounds, capture the whole bounds or a rectangle within them, then encode the returned image as PNG. The example below lists displays or saves a screenshot from a selected display. It also accounts for displays whose coordinates are negative or do not start at (0, 0).

Install the Go screenshot package

Use the focused github.com/kbinani/screenshot package when your program needs to capture a display or rectangular region without also taking on a broader desktop-automation library. In a Go module, add it with:

go get github.com/kbinani/screenshot

The project README lists Windows, Darwin, Linux, FreeBSD, OpenBSD, and NetBSD among its supported GOOS targets, and describes the implementation as cgo-free except for Darwin. Actual capture still depends on the operating system and session’s permissions and display-server behavior; check the project documentation for the environment you intend to ship on.

Runnable Go program: list displays or capture one

Save this as main.go. With no flags, it prints the active display indices and bounds. Pass -display and -out to save a PNG. Add all three region flags—-x, -y, and -w—plus -h to capture a rectangle; the region must fit inside the chosen display’s bounds.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
package main

import (
    "flag"
    "fmt"
    "image"
    "image/png"
    "os"

    "github.com/kbinani/screenshot"
)

func main() {
    display := flag.Int("display", -1, "display index; omit to list displays")
    out := flag.String("out", "screenshot.png", "output PNG file")
    x := flag.Int("x", 0, "region left coordinate in desktop coordinates")
    y := flag.Int("y", 0, "region top coordinate in desktop coordinates")
    w := flag.Int("w", 0, "region width; use with -x, -y, and -h")
    h := flag.Int("h", 0, "region height; use with -x, -y, and -w")
    flag.Parse()

    count := screenshot.NumActiveDisplays()
    if count == 0 {
        fail("no active displays found")
    }

    if *display < 0 {
        for i := 0; i < count; i++ {
            fmt.Printf("display %d: %vn", i, screenshot.GetDisplayBounds(i))
        }
        return
    }
    if *display >= count {
        fail("display index %d is out of range (found %d active displays)", *display, count)
    }

    bounds := screenshot.GetDisplayBounds(*display)
    rect := bounds
    if *w != 0 || *h != 0 || *x != 0 || *y != 0 {
        if *w <= 0 || *h <= 0 {
            fail("a region requires positive -w and -h values")
        }
        rect = image.Rect(*x, *y, *x+*w, *y+*h)
        if rect.Min.X < bounds.Min.X || rect.Min.Y < bounds.Min.Y ||
            rect.Max.X > bounds.Max.X || rect.Max.Y > bounds.Max.Y {
            fail("region %v is outside display %d bounds %v", rect, *display, bounds)
        }
    }

    img, err := screenshot.CaptureRect(rect)
    if err != nil {
        fail("capture %v: %v", rect, err)
    }

    file, err := os.Create(*out)
    if err != nil {
        fail("create %q: %v", *out, err)
    }
    if err := png.Encode(file, img); err != nil {
        _ = file.Close()
        fail("encode PNG: %v", err)
    }
    if err := file.Close(); err != nil {
        fail("close output file: %v", err)
    }
    fmt.Printf("saved %s (%dx%d)n", *out, img.Bounds().Dx(), img.Bounds().Dy())
}

func fail(format string, args ...any) {
    fmt.Fprintf(os.Stderr, format+"n", args...)
    os.Exit(1)
}

Run it from the module directory:

go run .
go run . -display 0 -out display-0.png
go run . -display 0 -x 100 -y 100 -w 800 -h 600 -out region.png

The first command prints bounds such as (-1920,0)-(0,1080) or (0,0)-(1920,1080), depending on the display arrangement. The exact values depend on the machine. Use the printed bounds to choose a region: the -x and -y flags are desktop coordinates, not offsets from the selected display’s upper-left corner. The program intentionally rejects a rectangle outside that display rather than silently clipping it.

How display enumeration and coordinates work

The package’s documented workflow is NumActiveDisplays, GetDisplayBounds(i), then CaptureRect(bounds). Each captured result is an image.Image, which Go’s image/png package can encode to a file. On a multi-monitor desktop, repeat the capture for each index if you want one output image per display; use distinct filenames, such as display-0.png and display-1.png.

The library documents the coordinate origin at the upper-left of the main display, with y increasing downward. A monitor positioned left of or above the main display can have negative x or y coordinates. That is why region coordinates should be based on the rectangles returned by GetDisplayBounds, not an assumed origin of zero. For example, if a display’s bounds begin at (-1920,0), its left edge is x = -1920 in the desktop coordinate system.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

To capture the entire virtual desktop as one image rather than one image per monitor, determine the union rectangle of all display bounds and pass that rectangle to CaptureRect. This is different from capturing one display at a time; monitor gaps or unusual layouts may affect the resulting image. The package README’s example demonstrates multiple displays and nonzero or negative coordinates, but does not establish how every operating-system layout or gap will appear in a combined capture.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Save another image format

The example writes PNG. The capture method returns an image, so the encoding step determines the output format. For JPEG, replace the PNG encoder with Go’s image/jpeg encoder. JPEG has a quality setting and is lossy; PNG preserves pixel values but may produce larger files for photographic content. Check encoder errors and close the output file in either case.

import "image/jpeg"

// After creating file and obtaining img:
if err := jpeg.Encode(file, img, &jpeg.Options{Quality: 85}); err != nil {
    _ = file.Close()
    return err
}

The short snippet above is an encoder substitution, not a separate complete program: keep the capture, file-creation, and error-handling steps from the runnable example. Standard Go’s image encoders are format-specific; do not change the file extension alone and expect the encoded bytes to change format.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

When RobotGo is a better fit

RobotGo bundles screen capture with mouse, keyboard, window, process, image, and bitmap functionality. Its package documentation exposes Capture and CaptureImg, and its screen example demonstrates full-screen or region capture, saving output, and iterating over displays. Consider it when screenshot capture is one part of a larger desktop-automation application. For a capture-only utility, compare its broader scope and platform setup with the focused package above.

RobotGo’s upstream README describes multiple backend and build choices. In Linux Wayland environments, it discusses a wlroots-oriented backend that depends on protocols such as zwlr_screencopy_v1, as well as portal/libei paths and differences across GNOME and KDE. It also says macOS capture requires Screen Recording permission. These details are release- and environment-sensitive: confirm the current RobotGo instructions for your selected version, build tags, compositor, and permission model before relying on a particular backend.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Consideration kbinani/screenshot RobotGo
Scope Focused display and rectangle capture. Capture within a broader desktop-automation library.
Capture API Enumerate displays, get bounds, capture a rectangle. Package docs expose Capture and CaptureImg.
Platform setup README lists Windows, Darwin, Linux, FreeBSD, OpenBSD, and NetBSD; cgo-free except Darwin, per project documentation. Backend, build, and permission choices vary; check the upstream README for the target environment.

Permissions, environment, and reliability

A successful build does not guarantee capture will work in every desktop session. A library can call the operating system’s capture facilities, but the session, compositor, or privacy settings may restrict access. On macOS, the RobotGo README specifically calls out Screen Recording permission. On Linux, distinguish X11 from Wayland and verify that the backend documented for your compositor is available; RobotGo’s README describes these differences explicitly. Do not infer support for a specific setup merely from a broad operating-system label.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

For an application that runs unattended, test under the same user, display server, permissions, and monitor arrangement that production will use. A headless process with no accessible desktop session is not equivalent to an interactive user session, and the cited project documentation does not promise that every headless environment can provide a meaningful desktop image.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

  • No active displays: NumActiveDisplays returns zero. Confirm the program is running in a logged-in graphical session with an attached or otherwise active display, rather than assuming an SSH or service process shares the user’s desktop.
  • Capture returns an error: Check the display index and rectangle first. Then confirm the operating system’s capture permission and, on Linux, the display-server backend and compositor support for the package or RobotGo build you selected.
  • Region is shifted or rejected: Compare the requested coordinates with GetDisplayBounds. Coordinates use the desktop coordinate space; a monitor to the left or above the main screen may begin at a negative coordinate. The sample validates that the rectangle is wholly within the chosen display.
  • PNG file is missing or empty: Check the output directory and permissions. The sample reports file creation, encoding, and close errors separately; a successful capture does not by itself mean the file was written successfully.
  • It works on one machine but not another: Record OS, display server, compositor, library version, build tags, and permissions. Confirm those specifics against the relevant project’s current documentation instead of treating “cross-platform” as a guarantee that all session backends behave identically.

Desktop screenshots versus live screen feeds

This workflow captures a still image and writes it to a file. A live feed means repeatedly obtaining frames and delivering or encoding them as a stream, which introduces timing, synchronization, and video-encoding concerns beyond a one-shot PNG capture. The cited screenshot package documentation establishes still-image capture, not a live-streaming API; do not treat a loop around CaptureRect as a complete, efficient video-capture pipeline without separately addressing those requirements.

Or skip the browser setup

If your actual input is a public webpage URL—not your local desktop—ScreenshotNeo is a URL-based website screenshot API, not a local monitor-capture library. One GET request returns an image or PDF; the following cURL example saves a WebP image. See the ScreenshotNeo API documentation for request options.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed. Its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000 shots. Sign up for 1,000 free screenshots a month with no card.

Frequently Asked Questions

Can the Go program capture a webpage without displaying it on my desktop?

The program shown captures a local display rectangle. Rendering a webpage from a URL without using the local desktop is a separate browser-rendering task; ScreenshotNeo’s URL-based API is one option for that different input.

Does this example capture every monitor into one file?

No. It captures one selected display or a region on that display. To create one file per monitor, run a capture for each display index and give each image a distinct filename.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.