[Python] Copy image to clipboard in python and Qt6 in linux

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    General overview


    The goal is pretty simple :

    1. copy image in the clipboard
    2. using ideally no graphical library related solution, or if it’s necessary Qt
    3. Working on Unices or ideally a no OS-related solution
    4. With just python tools, no subprocess to call an external no python command
    Working tries


    I was able to do it with several ways but none fulfilled these four constraints.

    The Gtk solution


    import gi
    gi.require_version("Gtk", "3.0")
    from gi.repository import Gtk, Gdk, GdkPixbuf
    from PIL import Image

    def copy_image_to_clipboard(image_path):
    # Chargin image with pillow
    image = Image.open(image_path)
    rgba_image = image.convert("RGBA")
    data = rgba_image.tobytes()

    # Creating a GTK compatible pixbuf
    pixbuf = GdkPixbuf.Pixbuf.new_from_data(
    data,
    GdkPixbuf.Colorspace.RGB,
    True, # has_alpha
    8, # bits_per_sample
    image.width,
    image.height,
    image.width * 4
    )

    # Getting the path
    clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
    clipboard.set_image(pixbuf)
    clipboard.store() # S'assurer que l'image reste après la fin du script

    # Example
    copy_image_to_clipboard("image.png")
    Gtk.main()


    This one works, but it doesn’t satisfied the 2d constraint cause it use Gtk tools and not Qt or a non-graphical library.

    The xclip with subprocess solution


    import subprocess

    def copy_image_to_clipboard(image_path):
    subprocess.run(["xclip", "-selection", "clipboard", "-t", "image/png", "-i", image_path])
    print(f"✅ Image copiée dans le presse-papier : {image_path}")

    copy_image_to_clipboard("/tmp/image.png")


    This other one also work but depend on xclip command and it’s OS related, so it infringe the 3d and 4th constraints

    The unworking Qt trie


    import sys
    from PyQt6 import QtCore, QtGui
    from PIL import Image

    def copy_image_to_clipboard(image_path):
    # Check if the image exists
    if not QtCore.QFile.exists(image_path):
    print(f"Error: the file {image_path} was not found.")
    return

    # Create the Qt application if it doesn't already exist
    if QtGui.QGuiApplication.instance() is None:
    app = QtGui.QGuiApplication(sys.argv)

    # Load the image with PIL and convert it to QImage
    image = Image.open(image_path).convert("RGBA")
    qimage = QtGui.QImage(image.tobytes(), image.width, image.height, QtGui.QImage.Format.Format_RGBA8888)

    # Check if the conversion was successful
    if qimage.isNull():
    print("Error: the conversion of the image to QImage failed.")
    return

    # Copy the image to the clipboard
    clipboard = QtGui.QGuiApplication.clipboard()
    clipboard.setImage(qimage)

    print(f"✅ Image copied to clipboard: {image_path}")

    # Example usage
    copy_image_to_clipboard("/tmp/image.png") # Replace with your image path


    This one is full Qt (2), it seams to be not OS related (3), use only python tools (4), but it doesn’t copy anything (The 1st constraint) so, it’s useless.

    The question


    How to copy image into clipboard using just Qt (and also other library for image processing or dedicated to clipboard management but not a full graphical library like Gtk) ?

    Continue reading...

Compartilhe esta Página