ImageGrab.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # screen grabber
  6. #
  7. # History:
  8. # 2001-04-26 fl created
  9. # 2001-09-17 fl use builtin driver, if present
  10. # 2002-11-19 fl added grabclipboard support
  11. #
  12. # Copyright (c) 2001-2002 by Secret Labs AB
  13. # Copyright (c) 2001-2002 by Fredrik Lundh
  14. #
  15. # See the README file for information on usage and redistribution.
  16. #
  17. from __future__ import annotations
  18. __lazy_modules__ = {"io", "shutil", "subprocess"}
  19. import io
  20. import os
  21. import shutil
  22. import subprocess
  23. import sys
  24. from . import Image
  25. TYPE_CHECKING = False
  26. if TYPE_CHECKING:
  27. from . import ImageWin
  28. def grab(
  29. bbox: tuple[int, int, int, int] | None = None,
  30. include_layered_windows: bool = False,
  31. all_screens: bool = False,
  32. xdisplay: str | None = None,
  33. window: int | ImageWin.HWND | None = None,
  34. *,
  35. scale_down: bool = False,
  36. ) -> Image.Image:
  37. im: Image.Image
  38. import tempfile
  39. if xdisplay is None:
  40. if sys.platform == "darwin":
  41. fh, filepath = tempfile.mkstemp(".png")
  42. os.close(fh)
  43. args = ["screencapture"]
  44. if window is not None:
  45. args += ["-l", str(window)]
  46. elif bbox:
  47. left, top, right, bottom = bbox
  48. args += ["-R", f"{left},{top},{right-left},{bottom-top}"]
  49. args += ["-x", filepath]
  50. retcode = subprocess.call(args)
  51. if retcode:
  52. raise subprocess.CalledProcessError(retcode, args)
  53. im = Image.open(filepath)
  54. im.load()
  55. os.unlink(filepath)
  56. if bbox:
  57. if window is not None:
  58. # Determine if the window was in Retina mode or not
  59. # by capturing it without the shadow,
  60. # and checking how different the width is
  61. fh, filepath = tempfile.mkstemp(".png")
  62. os.close(fh)
  63. args = ["screencapture", "-l", str(window), "-o", "-x", filepath]
  64. retcode = subprocess.call(args)
  65. if retcode:
  66. raise subprocess.CalledProcessError(retcode, args)
  67. with Image.open(filepath) as im_no_shadow:
  68. retina = im.width - im_no_shadow.width > 100
  69. os.unlink(filepath)
  70. # Since screencapture's -R does not work with -l,
  71. # crop the image manually
  72. if retina:
  73. left, top, right, bottom = bbox
  74. scale = 1 if scale_down else 2
  75. im_cropped = im.resize(
  76. ((right - left) * scale, (bottom - top) * scale),
  77. box=(left * 2, top * 2, right * 2, bottom * 2),
  78. )
  79. else:
  80. im_cropped = im.crop(bbox)
  81. im.close()
  82. return im_cropped
  83. elif scale_down:
  84. im_resized = im.resize((right - left, bottom - top))
  85. im.close()
  86. return im_resized
  87. return im
  88. elif sys.platform == "win32":
  89. if window is not None:
  90. all_screens = -1
  91. offset, size, data = Image.core.grabscreen_win32(
  92. include_layered_windows,
  93. all_screens,
  94. int(window) if window is not None else 0,
  95. )
  96. im = Image.frombytes(
  97. "RGB",
  98. size,
  99. data,
  100. # RGB, 32-bit line padding, origin lower left corner
  101. "raw",
  102. "BGR",
  103. (size[0] * 3 + 3) & -4,
  104. -1,
  105. )
  106. if bbox:
  107. x0, y0 = offset
  108. left, top, right, bottom = bbox
  109. im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
  110. return im
  111. # Cast to Optional[str] needed for Windows and macOS.
  112. display_name: str | None = xdisplay
  113. try:
  114. if not Image.core.HAVE_XCB:
  115. msg = "Pillow was built without XCB support"
  116. raise OSError(msg)
  117. size, data = Image.core.grabscreen_x11(display_name)
  118. except OSError:
  119. if display_name is None and sys.platform not in ("darwin", "win32"):
  120. if shutil.which("gnome-screenshot"):
  121. args = ["gnome-screenshot", "-f"]
  122. elif shutil.which("grim"):
  123. args = ["grim"]
  124. elif shutil.which("spectacle"):
  125. args = ["spectacle", "-n", "-b", "-f", "-o"]
  126. else:
  127. raise
  128. fh, filepath = tempfile.mkstemp(".png")
  129. os.close(fh)
  130. args.append(filepath)
  131. retcode = subprocess.call(args)
  132. if retcode:
  133. raise subprocess.CalledProcessError(retcode, args)
  134. im = Image.open(filepath)
  135. im.load()
  136. os.unlink(filepath)
  137. if bbox:
  138. im_cropped = im.crop(bbox)
  139. im.close()
  140. return im_cropped
  141. return im
  142. else:
  143. raise
  144. else:
  145. im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
  146. if bbox:
  147. im = im.crop(bbox)
  148. return im
  149. def grabclipboard() -> Image.Image | list[str] | None:
  150. if sys.platform == "darwin":
  151. p = subprocess.run(
  152. ["osascript", "-e", "get the clipboard as «class PNGf»"],
  153. capture_output=True,
  154. )
  155. if p.returncode != 0:
  156. return None
  157. import binascii
  158. data = io.BytesIO(binascii.unhexlify(p.stdout[11:-3]))
  159. return Image.open(data)
  160. elif sys.platform == "win32":
  161. format_name, data = Image.core.grabclipboard_win32()
  162. if format_name == "file": # CF_HDROP
  163. import struct
  164. o = struct.unpack_from("I", data)[0]
  165. if data[16] == 0:
  166. files = data[o:].decode("mbcs").split("\0")
  167. else:
  168. files = data[o:].decode("utf-16le").split("\0")
  169. return files[: files.index("")]
  170. if format_name in {"DIB", "PNG"}:
  171. return Image.open(io.BytesIO(data), formats=[format_name])
  172. return None
  173. else:
  174. if os.getenv("WAYLAND_DISPLAY"):
  175. session_type = "wayland"
  176. elif os.getenv("DISPLAY"):
  177. session_type = "x11"
  178. else: # Session type check failed
  179. session_type = None
  180. if shutil.which("wl-paste") and session_type in ("wayland", None):
  181. args = ["wl-paste", "-t", "image"]
  182. elif shutil.which("xclip") and session_type in ("x11", None):
  183. args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
  184. else:
  185. msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"
  186. raise NotImplementedError(msg)
  187. p = subprocess.run(args, capture_output=True)
  188. if p.returncode != 0:
  189. err = p.stderr
  190. for silent_error in [
  191. # wl-paste, when the clipboard is empty
  192. b"Nothing is copied",
  193. # Ubuntu/Debian wl-paste, when the clipboard is empty
  194. b"No selection",
  195. # Ubuntu/Debian wl-paste, when an image isn't available
  196. b"No suitable type of content copied",
  197. # wl-paste or Ubuntu/Debian xclip, when an image isn't available
  198. b" not available",
  199. # xclip, when an image isn't available
  200. b"cannot convert ",
  201. # xclip, when the clipboard isn't initialized
  202. b"xclip: Error: There is no owner for the ",
  203. ]:
  204. if silent_error in err:
  205. return None
  206. msg = f"{args[0]} error"
  207. if err:
  208. msg += f": {err.strip().decode()}"
  209. raise ChildProcessError(msg)
  210. data = io.BytesIO(p.stdout)
  211. im = Image.open(data)
  212. im.load()
  213. return im