Basic Image Operations

Python Pillow Color Conversions

Image Manipulation

Image Filtering

Image Enhancement and Correction

Image Analysis

Advanced Topics

  • Image Module
  • Python Pillow Useful Resources

    Selected Reading

    Python Pillow - ImageGrab.grabclipboard()Function



    The PIL.ImageGrab.grabclipboard() function is used to take a snapshot of the clipboard image, if available.

    On Linux, the function requires either wl-paste or xclip.

    Syntax

    Following is the syntax of the function −

    PIL.ImageGrab.grabclipboard()
    

    Return Value

    The return value of this function varies depending on the Operation system. Here are the key details −

    • Windows − Returns an image, a list of filenames, or None if the clipboard does not contain image data or filenames. If a list is returned, the filenames may not necessarily represent image files.

    • Mac − Returns an image or None if the clipboard does not contain image data.

    • Linux − Returns an image.

    Examples

    Example 1

    This code is a simple example of how to use the grabclipboard() method to fetch an image from the clipboard and display it.

    from PIL import Image, ImageGrab
    
    # Use the grabclipboard method to capture the clipboard image
    clipboard_image = ImageGrab.grabclipboard()
    
    # Display the captured image
    clipboard_image.show()
    

    Output

    AttributeError: 'NoneType' object has no attribute 'show'
    

    This error indicates that no image data was copied to the clipboard.

    Example 2

    To prevent the AttributeError and handle the case where grabclipboard() returns None, you can check if the result is not None before attempting to use the show() method.

    from PIL import ImageGrab
    
    # Take a snapshot of the clipboard image
    clipboard_image = ImageGrab.grabclipboard()
    
    # Check clipboard_image object
    if clipboard_image:
       # Display or process the clipboard image as needed
       clipboard_image.show()
    else:
       print("The clipboard does not contain image data.")
    
    

    Output

    clipboard image

    This example prevents the AttributeError and handles the case the clipboard contains non-image data, such as text.

    Example 3

    The example is similar to the previous one, but it explicitly checks whether the clipboard object is an image, instead of directly checking if the clipboard object is not None. This uses isinstance() function.

    from PIL import ImageGrab
    
    # Take a snapshot of the clipboard image
    clipboard_image = ImageGrab.grabclipboard()
    
    # Check for the clipboard object is an image or not
    if isinstance(clipboard_image, Image.Image):
        
       # Display or save the clipboard image
       clipboard_image.show()
    else:
       print("The clipboard does not contain image data.")
    

    Output

    snapshot clipboard image
    python_pillow_function_reference.htm
    Advertisements