Last active
January 22, 2024 18:38
-
-
Save Saba-Sabato/3ad3df938c5b576bc50c26d180820dce to your computer and use it in GitHub Desktop.
Take a fullscreen screenshot on MacOS, using PyObjC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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