grab.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. """
  2. PIL-based formats to take screenshots and grab from the clipboard.
  3. """
  4. import threading
  5. import numpy as np
  6. from ..core import Format
  7. class BaseGrabFormat(Format):
  8. """Base format for grab formats."""
  9. _pillow_imported = False
  10. _ImageGrab = None
  11. def __init__(self, *args, **kwargs):
  12. super(BaseGrabFormat, self).__init__(*args, **kwargs)
  13. self._lock = threading.RLock()
  14. def _can_write(self, request):
  15. return False
  16. def _init_pillow(self):
  17. with self._lock:
  18. if not self._pillow_imported:
  19. self._pillow_imported = True # more like tried to import
  20. import PIL
  21. if not hasattr(PIL, "__version__"): # pragma: no cover
  22. raise ImportError("Imageio Pillow requires " "Pillow, not PIL!")
  23. try:
  24. from PIL import ImageGrab
  25. except ImportError:
  26. return None
  27. self._ImageGrab = ImageGrab
  28. return self._ImageGrab
  29. class Reader(Format.Reader):
  30. def _open(self):
  31. pass
  32. def _close(self):
  33. pass
  34. def _get_data(self, index):
  35. return self.format._get_data(index)
  36. class ScreenGrabFormat(BaseGrabFormat):
  37. """The ScreenGrabFormat provided a means to grab screenshots using
  38. the uri of "<screen>".
  39. This functionality is provided via Pillow. Note that "<screen>" is
  40. only supported on Windows and OS X.
  41. Parameters for reading
  42. ----------------------
  43. No parameters.
  44. """
  45. def _can_read(self, request):
  46. if request.filename != "<screen>":
  47. return False
  48. return bool(self._init_pillow())
  49. def _get_data(self, index):
  50. ImageGrab = self._init_pillow()
  51. assert ImageGrab
  52. pil_im = ImageGrab.grab()
  53. assert pil_im is not None
  54. im = np.asarray(pil_im)
  55. return im, {}
  56. class ClipboardGrabFormat(BaseGrabFormat):
  57. """The ClipboardGrabFormat provided a means to grab image data from
  58. the clipboard, using the uri "<clipboard>"
  59. This functionality is provided via Pillow. Note that "<clipboard>" is
  60. only supported on Windows.
  61. Parameters for reading
  62. ----------------------
  63. No parameters.
  64. """
  65. def _can_read(self, request):
  66. if request.filename != "<clipboard>":
  67. return False
  68. return bool(self._init_pillow())
  69. def _get_data(self, index):
  70. ImageGrab = self._init_pillow()
  71. assert ImageGrab
  72. pil_im = ImageGrab.grabclipboard()
  73. if pil_im is None:
  74. raise RuntimeError(
  75. "There seems to be no image data on the " "clipboard now."
  76. )
  77. im = np.asarray(pil_im)
  78. return im, {}