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.

80 lines
2.1 KiB

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