下面是macOS的代码,旨在获取整个屏幕和框架中每个窗口的屏幕截图,然后将其保存到桌面。当调用屏幕截图功能时,什么都没有发生。我试图将图像记录到控制台以检查正在保存的内容,并且看起来宽度和高度为1x1。有什么想法会导致这种情况吗?
func screenshot(){
let windowImage: CGImage =
CGWindowListCreateImage(.infinite, .optionIncludingWindow, kCGNullWindowID,
[.boundsIgnoreFraming, .nominalResolution])!
print(windowImage)
let unixTimestamp = CreateTimeStamp()
let filename = NSHomeDirectory()
var paths = NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true) as [String]
let homeDirURL = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("/Desktop/screenshot.jpg")
print(homeDirURL.path)
let bitmapRep = NSBitmapImageRep(cgImage: windowImage)
let jpegData = bitmapRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
do {
try jpegData.write(to: homeDirURL, options: .atomic)
} catch {
print("error: \(error)")
}
}
打印到控制台的图像:
<CGImage 0x101116a40> (DP)
<<CGColorSpace 0x600002601ec0> (kCGColorSpaceDeviceRGB)>
width = 1, height = 1, bpc = 8, bpp = 32, row bytes = 4
kCGImageAlphaPremultipliedFirst | 0 (default byte order) | kCGImagePixelFormatPacked
is mask? No, has masking color? No, has soft mask? No, has matte? No, should interpolate? No
/Users/adrianalonzo//Desktop/screenshot.jpg
更新:修复了屏幕截图参数。代码现在可以使用(:
func screenshot(){
let windowImage: CGImage = CGWindowListCreateImage(CGRect.infinite, .optionAll, kCGNullWindowID, .nominalResolution)!
print(windowImage)
let unixTimestamp = CreateTimeStamp()
let filename = NSHomeDirectory()
var paths = NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true) as [String]
let homeDirURL = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("/Desktop/screenshot_\(unixTimestamp).jpg")
print(homeDirURL.path)
let bitmapRep = NSBitmapImageRep(cgImage: windowImage)
let jpegData = bitmapRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
do {
try jpegData.write(to: homeDirURL, options: .atomic)
} catch {
print("error: \(error)")
}
}
func CreateTimeStamp() -> Int32
{
return Int32(Date().timeIntervalSince1970)
}