Skip to content

Instantly share code, notes, and snippets.

@Saba-Sabato
Last active January 22, 2024 18:38
Show Gist options
  • Save Saba-Sabato/3ad3df938c5b576bc50c26d180820dce to your computer and use it in GitHub Desktop.
Save Saba-Sabato/3ad3df938c5b576bc50c26d180820dce to your computer and use it in GitHub Desktop.
Take a fullscreen screenshot on MacOS, using PyObjC
# Packages required:
# pyobjc-framework-Quartz
# pyobjc-framework-UniformTypeIdentifiers
from pathlib import Path
import Foundation
import Quartz
import UniformTypeIdentifiers
import objc
def write_screenshot_to_file(path: Path | str):
screenshot = get_screenshot()
url = convert_path_to_ns_url(path)
result = write_image_to_file(screenshot, url)
assert result is True, "Failed writing screenshot to file"
return
def write_image_to_file(image, path):
dest = Quartz.CGImageDestinationCreateWithURL(
path, UniformTypeIdentifiers.UTTypeJPEG.identifier(), 1, None
)
assert dest is not None, "Error creating destination, check parameters?"
Quartz.CGImageDestinationAddImage(dest, image, None)
result = Quartz.CGImageDestinationFinalize(dest)
return result
def get_screenshot():
return Quartz.CGDisplayCreateImage(Quartz.CGMainDisplayID())
def convert_path_to_ns_url(path: Path | str):
if isinstance(path, str):
path = Path(path)
url = Foundation.NSURL.fileURLWithPath_(str(path.absolute()))
return url
def main(path: Path | str):
with objc.autorelease_pool():
write_screenshot_to_file(path)
# sleep(5)
if __name__ == "__main__":
main(Path.cwd() / "screenshot.jpeg")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment