【发布时间】:2021-03-29 17:28:55
【问题描述】:
我想使用 golang 语言制作我的 mac 桌面的屏幕截图。有一个很好且简单的工具:https://github.com/kbinani/screenshot 我使用它已经有一段时间了,但最近我尝试再次使用它,并注意到我的两台 macbook(big sur 和 catalina)有一个奇怪的行为。
这是一个简单的代码:
package main
import (
"fmt"
"github.com/kbinani/screenshot"
"image/png"
"os"
)
func main(){
bounds := screenshot.GetDisplayBounds(0)
img, err := screenshot.CaptureRect(bounds)
if err != nil {
panic(err)
}
fileName := fmt.Sprintf("%d_%dx%d.png", 0, bounds.Dx(), bounds.Dy())
file, _ := os.Create(fileName)
defer file.Close()
png.Encode(file, img)
fmt.Printf("#%d : %v \"%s\"\n", 0, bounds, fileName)
}
上面的代码应该捕获第一个屏幕并将文件保存为接近二进制的“0_2560x1440.png”。 当我从 Jetbrains Goland IDE 运行二进制文件或使用 在 Jetbrains Goland IDE 终端中运行 main.go 命令一切正常。但是,如果我从默认终端(或 iTerm)运行 binary 或 go run main.go,我将收到没有任何窗口的屏幕截图,只是一个没有任何 winodws 或 foldres 的普通桌面。
这是什么原因?从 IDE 终端或 OS 终端运行二进制文件有什么区别?
经过一番考虑,我认为 golang 截图库中的某个地方可能存在错误。我尝试使用 OSX api 运行另一个代码:
package main
// To use the two libraries we need to define the respective flags, include the required header files and import "C" immediately after
import (
// #cgo LDFLAGS: -framework CoreGraphics
// #cgo LDFLAGS: -framework CoreFoundation
// #include <CoreGraphics/CoreGraphics.h>
// #include <CoreFoundation/CoreFoundation.h>
"C"
"image"
"image/png"
"os"
"reflect"
"unsafe"
// other packages...
)
func main() {
displayID := C.CGMainDisplayID()
width := int(C.CGDisplayPixelsWide(displayID))
height := int(C.CGDisplayPixelsHigh(displayID))
rawData := C.CGDataProviderCopyData(C.CGImageGetDataProvider(C.CGDisplayCreateImage(displayID)))
length := int(C.CFDataGetLength(rawData))
ptr := unsafe.Pointer(C.CFDataGetBytePtr(rawData))
var slice []byte
hdrp := (*reflect.SliceHeader)(unsafe.Pointer(&slice))
hdrp.Data = uintptr(ptr)
hdrp.Len = length
hdrp.Cap = length
imageBytes := make([]byte, length)
for i := 0; i < length; i += 4 {
imageBytes[i], imageBytes[i+2], imageBytes[i+1], imageBytes[i+3] = slice[i+2], slice[i], slice[i+1], slice[i+3]
}
//C.CFRelease(rawData)
img := &image.RGBA{Pix: imageBytes, Stride: 4 * width, Rect: image.Rect(0, 0, width, height)}
// There we go, we can now save or process the image further
file, err := os.Create("file.png")
if err != nil {
panic(err)
}
defer file.Close()
if err := png.Encode(file, img); err != nil {
panic(err)
}
}
此代码给出相同的结果。在 IDE 终端中运行 - 正常行为。在其他地方运行 - 屏幕截图现在有内容。
请帮我揭开它的神秘面纱。
【问题讨论】:
标签: go core-graphics screenshot