You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImageGrab.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # screen grabber (macOS and Windows only)
  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 . import Image
  18. import sys
  19. if sys.platform == "win32":
  20. grabber = Image.core.grabscreen
  21. elif sys.platform == "darwin":
  22. import os
  23. import tempfile
  24. import subprocess
  25. else:
  26. raise ImportError("ImageGrab is macOS and Windows only")
  27. def grab(bbox=None, include_layered_windows=False):
  28. if sys.platform == "darwin":
  29. fh, filepath = tempfile.mkstemp(".png")
  30. os.close(fh)
  31. subprocess.call(["screencapture", "-x", filepath])
  32. im = Image.open(filepath)
  33. im.load()
  34. os.unlink(filepath)
  35. else:
  36. size, data = grabber(include_layered_windows)
  37. im = Image.frombytes(
  38. "RGB",
  39. size,
  40. data,
  41. # RGB, 32-bit line padding, origin lower left corner
  42. "raw",
  43. "BGR",
  44. (size[0] * 3 + 3) & -4,
  45. -1,
  46. )
  47. if bbox:
  48. im = im.crop(bbox)
  49. return im
  50. def grabclipboard():
  51. if sys.platform == "darwin":
  52. fh, filepath = tempfile.mkstemp(".jpg")
  53. os.close(fh)
  54. commands = [
  55. 'set theFile to (open for access POSIX file "'
  56. + filepath
  57. + '" with write permission)',
  58. "try",
  59. " write (the clipboard as JPEG picture) to theFile",
  60. "end try",
  61. "close access theFile",
  62. ]
  63. script = ["osascript"]
  64. for command in commands:
  65. script += ["-e", command]
  66. subprocess.call(script)
  67. im = None
  68. if os.stat(filepath).st_size != 0:
  69. im = Image.open(filepath)
  70. im.load()
  71. os.unlink(filepath)
  72. return im
  73. else:
  74. data = Image.core.grabclipboard()
  75. if isinstance(data, bytes):
  76. from . import BmpImagePlugin
  77. import io
  78. return BmpImagePlugin.DibImageFile(io.BytesIO(data))
  79. return data