Created
January 17, 2025 13:47
-
-
Save kolibril13/e3ad8de7c3de3cea1d19465f9cf7df57 to your computer and use it in GitHub Desktop.
clipboard from png to jpeg
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
# /// script | |
# requires-python = ">=3.12" | |
# dependencies = [ | |
# "pillow", | |
# "pyobjc-framework-Quartz", | |
# ] | |
# /// | |
from pathlib import Path | |
from PIL import Image | |
from io import BytesIO | |
import AppKit | |
import sys | |
# Save PNG from clipboard to JPEG on Desktop | |
clipboard = AppKit.NSPasteboard.generalPasteboard() | |
png_data = clipboard.dataForType_(AppKit.NSPasteboardTypePNG) | |
if not png_data: | |
print("No PNG in clipboard.") | |
sys.exit(0) # Stop execution if no PNG is found | |
else: | |
img = Image.open(BytesIO(bytes(png_data))).convert("RGB") | |
jpeg_path = Path.home() / "Desktop" / "clipboard_image.jpeg" | |
img.save(jpeg_path, "JPEG", quality=70) | |
print(f"Saved JPEG to {jpeg_path}") | |
# Copy JPEG from Desktop to clipboard | |
if not jpeg_path.exists(): | |
print(f"File not found: {jpeg_path}") | |
else: | |
with open(jpeg_path, "rb") as f: | |
jpeg_data = f.read() | |
ns_data = AppKit.NSData.dataWithBytes_length_(jpeg_data, len(jpeg_data)) | |
clipboard.declareTypes_owner_(["public.jpeg"], None) | |
clipboard.setData_forType_(ns_data, "public.jpeg") | |
print(f"Copied JPEG from {jpeg_path} to clipboard") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment