|
1 | 1 | import io |
2 | | -from PIL import Image |
| 2 | +from typing import Union |
3 | 3 |
|
4 | | -from .. import json |
| 4 | +from .. import json, optional_features |
5 | 5 | from ..logging import log |
6 | 6 | from .javascript import run_javascript |
7 | 7 |
|
| 8 | +try: |
| 9 | + from PIL import Image as PIL_Image |
| 10 | + optional_features.register('pillow') |
| 11 | +except ImportError: |
| 12 | + pass |
| 13 | + |
8 | 14 |
|
9 | 15 | async def read() -> str: |
10 | 16 | """Read text from the clipboard. |
@@ -41,30 +47,28 @@ def write(text: str) -> None: |
41 | 47 | ''') |
42 | 48 |
|
43 | 49 |
|
44 | | -async def read_image() -> Image.Image | None: |
45 | | - """ |
46 | | - Read images from the clipboard. |
47 | | - Note: This function only works in secure contexts (HTTPS or localhost). |
| 50 | +async def read_image() -> Union['PIL_Image.Image', None]: |
| 51 | + """Read PIL images from the clipboard. |
| 52 | +
|
| 53 | + Note: This function only works in secure contexts (HTTPS or localhost) and requires Pillow to be installed. |
48 | 54 | """ |
| 55 | + if not optional_features.has('pillow'): |
| 56 | + log.warning('Pillow is not installed, so we cannot read images from the clipboard.') |
| 57 | + return None |
49 | 58 | content = await run_javascript(''' |
50 | 59 | if (navigator.clipboard) { |
51 | | - var items = await navigator.clipboard.read() |
52 | | - var images = [] |
53 | | - for(var item of items){ |
54 | | - if(item.types.length>0 && /^image/.test(item.types[0])){ |
55 | | - var blob = await item.getType(item.types[0]) |
56 | | - images.push(blob) |
57 | | - break |
| 60 | + const items = await navigator.clipboard.read(); |
| 61 | + for (const item of items) { |
| 62 | + if (item.types.length > 0 && /^image/.test(item.types[0])) { |
| 63 | + return await item.getType(item.types[0]); |
58 | 64 | } |
59 | 65 | } |
60 | | - //console.log(images) |
61 | | - return images |
62 | 66 | } |
63 | 67 | else { |
64 | | - console.error('Clipboard API is only available in secure contexts (HTTPS or localhost).') |
65 | | - return [] |
| 68 | + console.error('Clipboard API is only available in secure contexts (HTTPS or localhost).'); |
66 | 69 | } |
67 | 70 | ''', timeout=5) |
68 | | - if content: |
69 | | - buffer = io.BytesIO(content[0]) |
70 | | - return Image.open(buffer) |
| 71 | + if not content: |
| 72 | + return None |
| 73 | + buffer = io.BytesIO(content) |
| 74 | + return PIL_Image.open(buffer) |
0 commit comments