Pythonista-Issues icon indicating copy to clipboard operation
Pythonista-Issues copied to clipboard

Adding image to clipboard fails in Pythonista 3.4

Open felciano opened this issue 2 years ago • 0 comments
trafficstars

I'm trying to use Pythonista 3.4 to push some data to the clipboard, and am running into an error. The code below reproduces the problem: if I am in an app that allows you to share an image (e.g. for a social media post or similar) and I share that image with this Pythonista code, I get the following output:

Starting test
Setting clipboard image
Traceback (most recent call last):
  File "/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents//pythonista-scripts/clipboard-image-test.py", line 24, in <module>
    main()
  File "/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents//pythonista-scripts/clipboard-image-test.py", line 17, in main
    r1 = clipboard.set_image(my_image, format="png", jpeg_quality=1.0)
  File "/var/containers/Bundle/Application/B859D305-94CD-48F6-8589-AE439D2CCB7E/Pythonista3.app/Frameworks/Py3Kit.framework/pylib/site-packages/pythonista/clipboard.py", line 55, in set_image
    image_data = rgba_image.tostring()
  File "/var/containers/Bundle/Application/B859D305-94CD-48F6-8589-AE439D2CCB7E/Pythonista3.app/Frameworks/Py3Kit.framework/pylib/site-packages/PIL/Image.py", line 520, in __getattr__
    raise AttributeError(name)
AttributeError: tostring

It looks like Pythonista's clipboard.py is calling a rgba_image.tostring() method which no longer exists in the version of PIL shipping with Pythonista 3.4.

Sample code is below.

import importlib
import importlib.util

def main():
    print("Starting test")
    # check to see if appex library is available
    appex_spec = importlib.util.find_spec("appex")
    FOUND_APPEX_LIBRARY = appex_spec is not None
    if FOUND_APPEX_LIBRARY:
        import appex
        import clipboard
        import shortcuts

        if appex.is_running_extension():
            my_image = appex.get_image()
            print("Setting clipboard image")
            r1 = clipboard.set_image(my_image, format="png", jpeg_quality=1.0)
            print("Finished setting clipboard image")
            
        else:
            print("This demo is for Pythonista running in an extension")

if __name__ == "__main__":
    main()

Workaround is to retrieve a ui image instead of a PIL image:

my_image = appex.get_image(image_type='ui')

felciano avatar May 17 '23 17:05 felciano