Repository: python-pillow/Pillow

Issue:
`wl-paste` with image copied from browser results in `ImageGrab.grabclipboard` error 
<!--
Thank you for reporting an issue.

Follow these guidelines to ensure your issue is handled properly.

If you have a ...

1.  General question: consider asking the question on Stack Overflow
    with the python-imaging-library tag:

    * https://stackoverflow.com/questions/tagged/python-imaging-library

    Do not ask a question in both places.

    If you think you have found a bug or have an unexplained exception
    then file a bug report here.

2.  Bug report: include a self-contained, copy-pastable example that
    generates the issue if possible. Be concise with code posted.
    Guidelines on how to provide a good bug report:

    * https://stackoverflow.com/help/mcve

    Bug reports which follow these guidelines are easier to diagnose,
    and are often handled much more quickly.

3.  Feature request: do a quick search of existing issues
    to make sure this has not been asked before.

We know asking good questions takes effort, and we appreciate your time.
Thank you.
-->

### What did you do?

When source application offered multiple MIME type, `wl-paste` without `-t mime/type` maybe result in other MEME type instead of image. `ImageGrab.grabclipboard` use only `wl-paste` without arguments, which reports error whenever calling it with multiple MEME type. For example, open some website with images, copy the image, it will offer multiple MIME type.

### What did you expect to happen?

No error reports.

### What actually happened?

Error reports like this:

```
Traceback (most recent call last):
  File "/home/user/workspace/grab.py", line 9, in <module>
    main()
  File "/home/user/workspace/grab.py", line 5, in main
    ImageGrab.grabclipboard()
  File "/home/user/.local/lib/python3.10/site-packages/PIL/ImageGrab.py", line 146, in grabclipboard
    im = Image.open(filepath)
  File "/home/user/.local/lib/python3.10/site-packages/PIL/Image.py", line 3298, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file '/tmp/tmpvi9tcfs3'
```

### What are your OS, Python and Pillow versions?

* OS: Arch Linux
* Python: CPython 3.10.10
* Pillow: 9.5.0

<!--
Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive.

The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as Plone, Django, or Buildout, try to replicate the issue just using Pillow.
-->

```python
from PIL import ImageGrab


def main():
    ImageGrab.grabclipboard()


if __name__ == "__main__":
    main()
```



Discussion:

Resolving patch:
diff --git a/src/PIL/ImageGrab.py b/src/PIL/ImageGrab.py
--- a/src/PIL/ImageGrab.py
+++ b/src/PIL/ImageGrab.py
@@ -142,7 +142,18 @@ def grabclipboard():
         return None
     else:
         if shutil.which("wl-paste"):
+            output = subprocess.check_output(["wl-paste", "-l"]).decode()
+            mimetypes = output.splitlines()
+            if "image/png" in mimetypes:
+                mimetype = "image/png"
+            elif mimetypes:
+                mimetype = mimetypes[0]
+            else:
+                mimetype = None
+
             args = ["wl-paste"]
+            if mimetype:
+                args.extend(["-t", mimetype])
         elif shutil.which("xclip"):
             args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
         else:


Test patch:
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -84,7 +84,9 @@ jobs:
           python3 -m pip install pytest-reverse
         fi
         if [ "${{ matrix.os }}" = "ubuntu-latest" ]; then
-          xvfb-run -s '-screen 0 1024x768x24' .ci/test.sh
+          xvfb-run -s '-screen 0 1024x768x24' sway&
+          export WAYLAND_DISPLAY=wayland-1
+          .ci/test.sh
         else
           .ci/test.sh
         fi
diff --git a/Tests/test_imagegrab.py b/Tests/test_imagegrab.py
--- a/Tests/test_imagegrab.py
+++ b/Tests/test_imagegrab.py
@@ -98,3 +98,18 @@ def test_grabclipboard_png(self):
 
         im = ImageGrab.grabclipboard()
         assert_image_equal_tofile(im, "Tests/images/hopper.png")
+
+    @pytest.mark.skipif(
+        (
+            sys.platform != "linux"
+            or not all(shutil.which(cmd) for cmd in ("wl-paste", "wl-copy"))
+        ),
+        reason="Linux with wl-clipboard only",
+    )
+    @pytest.mark.parametrize("ext", ("gif", "png", "ico"))
+    def test_grabclipboard_wl_clipboard(self, ext):
+        image_path = "Tests/images/hopper." + ext
+        with open(image_path, "rb") as fp:
+            subprocess.call(["wl-copy"], stdin=fp)
+        im = ImageGrab.grabclipboard()
+        assert_image_equal_tofile(im, image_path)