Screenshot with wayland

Hey guys,
I want to capture screen with golang.
Everything in X11 is ok. But when in wayland, I got black screen
I try to capture screen via DBUS. It captured screen
But I want capture screen and save to file in same folder (without flash + popup)

Please help me fix it
This is my code I using

package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/godbus/dbus"
)

func main() {
	conn, err := dbus.SessionBus()
	if err != nil {
		log.Fatalf("Failed to connect to session bus: %v", err)
	}
	defer conn.Close()

	dest := "org.freedesktop.portal.Desktop"
	path := "/org/freedesktop/portal/desktop"
	iface := "org.freedesktop.portal.Screenshot"
	options := map[string]dbus.Variant{
		"Path":  dbus.MakeVariant("/home/capture-wayland/screenshot.png"),
		"Flash": dbus.MakeVariant(false),
	}

	obj := conn.Object(dest, dbus.ObjectPath(path))
	caller := obj.Call(iface+".Screenshot", 0, "", options)

	fmt.Println(caller)
	fmt.Println(caller.Path)
	fmt.Println(caller.Destination)
	fmt.Println(caller.Method)
	fmt.Println(caller.Args)
	var response map[string]dbus.Variant
	// caller.Store(&response)
	// fmt.Println("response:", response)
	// a, _ := json.Marshal(caller)
	// fmt.Println("caller string:", string(a))
	_ = obj.Call(iface+".Screenshot", 1, "", options).Store(&response)
	fmt.Println(response)
	if err != nil {
		log.Fatalf("Failed to call Screenshot method: %v", err)
	}

	uri, ok := response["uri"]
	if !ok {
		log.Fatal("No URI found in the response")
	}

	// Download the image from the URI and save it to image.png
	downloadAndSave(uri.Value().(string), "image.png")
}

func downloadAndSave(url, filename string) {
	resp, err := http.Get(url)
	if err != nil {
		log.Fatalf("Failed to download the image: %v", err)
	}
	defer resp.Body.Close()

	out, err := os.Create(filename)
	if err != nil {
		log.Fatalf("Failed to create the image file: %v", err)
	}
	defer out.Close()

	_, err = io.Copy(out, resp.Body)
	if err != nil {
		log.Fatalf("Failed to save the image: %v", err)
	}
	fmt.Println("Saved screenshot to", filename)
}
1 Like

A different route than through dbus might be to use this library, which I have successfully used on both Windows and Darwin so I’m not sure it works on X or Wayland.

I already use this library. It doesn’t work with Wayland so I change to use dbus

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.