File: grab.py

package info (click to toggle)
python-imageio 2.4.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 4,824 kB
  • sloc: python: 18,306; makefile: 145
file content (125 lines) | stat: -rw-r--r-- 3,332 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""
PIL-based formats to take screenshots and grab from the clipboard.
"""

from __future__ import absolute_import, print_function, division

import threading

import numpy as np

from .. import formats
from ..core import Format


class BaseGrabFormat(Format):
    """ Base format for grab formats.
    """

    _pillow_imported = False
    _ImageGrab = None

    def __init__(self, *args, **kwargs):
        super(BaseGrabFormat, self).__init__(*args, **kwargs)
        self._lock = threading.RLock()

    def _can_write(self, request):
        return False

    def _init_pillow(self):
        with self._lock:
            if not self._pillow_imported:
                self._pillow_imported = True  # more like tried to import
                import PIL

                if not hasattr(PIL, "__version__"):  # pragma: no cover
                    raise ImportError("Imageio Pillow requires " "Pillow, not PIL!")
                try:
                    from PIL import ImageGrab
                except ImportError:
                    return None
                self._ImageGrab = ImageGrab
        return self._ImageGrab

    class Reader(Format.Reader):
        def _open(self):
            pass

        def _close(self):
            pass

        def _get_data(self, index):
            return self.format._get_data(index)


class ScreenGrabFormat(BaseGrabFormat):
    """ The ScreenGrabFormat provided a means to grab screenshots using
    the uri of "<screen>".
    
    This functionality is provided via Pillow. Note that "<screen>" is
    only supported on Windows and OS X.
    
    Parameters for reading
    ----------------------
    No parameters.
    """

    def _can_read(self, request):
        if request.mode[1] not in "i?":
            return False
        if request.filename != "<screen>":
            return False
        return bool(self._init_pillow())

    def _get_data(self, index):
        ImageGrab = self._init_pillow()
        assert ImageGrab

        pil_im = ImageGrab.grab()
        assert pil_im is not None
        im = np.asarray(pil_im)
        return im, {}


class ClipboardGrabFormat(BaseGrabFormat):
    """ The ClipboardGrabFormat provided a means to grab image data from
    the clipboard, using the uri "<clipboard>"
    
    This functionality is provided via Pillow. Note that "<clipboard>" is
    only supported on Windows.
    
    Parameters for reading
    ----------------------
    No parameters.
    """

    def _can_read(self, request):
        if request.mode[1] not in "i?":
            return False
        if request.filename != "<clipboard>":
            return False
        return bool(self._init_pillow())

    def _get_data(self, index):
        ImageGrab = self._init_pillow()
        assert ImageGrab

        pil_im = ImageGrab.grabclipboard()
        if pil_im is None:
            raise RuntimeError(
                "There seems to be no image data on the " "clipboard now."
            )
        im = np.asarray(pil_im)
        return im, {}


# Register. You register an *instance* of a Format class.
format = ScreenGrabFormat(
    "screengrab", "Grab screenshots (Windows and OS X only)", [], "i"
)
formats.add_format(format)

format = ClipboardGrabFormat(
    "clipboardgrab", "Grab from clipboard (Windows only)", [], "i"
)
formats.add_format(format)