ImageShow.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # im.show() drivers
  6. #
  7. # History:
  8. # 2008-04-06 fl Created
  9. #
  10. # Copyright (c) Secret Labs AB 2008.
  11. #
  12. # See the README file for information on usage and redistribution.
  13. #
  14. from __future__ import annotations
  15. import os
  16. import shutil
  17. import subprocess
  18. import sys
  19. from shlex import quote
  20. from . import Image
  21. _viewers = []
  22. def register(viewer, order=1):
  23. """
  24. The :py:func:`register` function is used to register additional viewers::
  25. from PIL import ImageShow
  26. ImageShow.register(MyViewer()) # MyViewer will be used as a last resort
  27. ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised
  28. ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised
  29. :param viewer: The viewer to be registered.
  30. :param order:
  31. Zero or a negative integer to prepend this viewer to the list,
  32. a positive integer to append it.
  33. """
  34. try:
  35. if issubclass(viewer, Viewer):
  36. viewer = viewer()
  37. except TypeError:
  38. pass # raised if viewer wasn't a class
  39. if order > 0:
  40. _viewers.append(viewer)
  41. else:
  42. _viewers.insert(0, viewer)
  43. def show(image, title=None, **options):
  44. r"""
  45. Display a given image.
  46. :param image: An image object.
  47. :param title: Optional title. Not all viewers can display the title.
  48. :param \**options: Additional viewer options.
  49. :returns: ``True`` if a suitable viewer was found, ``False`` otherwise.
  50. """
  51. for viewer in _viewers:
  52. if viewer.show(image, title=title, **options):
  53. return True
  54. return False
  55. class Viewer:
  56. """Base class for viewers."""
  57. # main api
  58. def show(self, image, **options):
  59. """
  60. The main function for displaying an image.
  61. Converts the given image to the target format and displays it.
  62. """
  63. if not (
  64. image.mode in ("1", "RGBA")
  65. or (self.format == "PNG" and image.mode in ("I;16", "LA"))
  66. ):
  67. base = Image.getmodebase(image.mode)
  68. if image.mode != base:
  69. image = image.convert(base)
  70. return self.show_image(image, **options)
  71. # hook methods
  72. format = None
  73. """The format to convert the image into."""
  74. options = {}
  75. """Additional options used to convert the image."""
  76. def get_format(self, image):
  77. """Return format name, or ``None`` to save as PGM/PPM."""
  78. return self.format
  79. def get_command(self, file, **options):
  80. """
  81. Returns the command used to display the file.
  82. Not implemented in the base class.
  83. """
  84. msg = "unavailable in base viewer"
  85. raise NotImplementedError(msg)
  86. def save_image(self, image):
  87. """Save to temporary file and return filename."""
  88. return image._dump(format=self.get_format(image), **self.options)
  89. def show_image(self, image, **options):
  90. """Display the given image."""
  91. return self.show_file(self.save_image(image), **options)
  92. def show_file(self, path, **options):
  93. """
  94. Display given file.
  95. """
  96. os.system(self.get_command(path, **options)) # nosec
  97. return 1
  98. # --------------------------------------------------------------------
  99. class WindowsViewer(Viewer):
  100. """The default viewer on Windows is the default system application for PNG files."""
  101. format = "PNG"
  102. options = {"compress_level": 1, "save_all": True}
  103. def get_command(self, file, **options):
  104. return (
  105. f'start "Pillow" /WAIT "{file}" '
  106. "&& ping -n 4 127.0.0.1 >NUL "
  107. f'&& del /f "{file}"'
  108. )
  109. if sys.platform == "win32":
  110. register(WindowsViewer)
  111. class MacViewer(Viewer):
  112. """The default viewer on macOS using ``Preview.app``."""
  113. format = "PNG"
  114. options = {"compress_level": 1, "save_all": True}
  115. def get_command(self, file, **options):
  116. # on darwin open returns immediately resulting in the temp
  117. # file removal while app is opening
  118. command = "open -a Preview.app"
  119. command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
  120. return command
  121. def show_file(self, path, **options):
  122. """
  123. Display given file.
  124. """
  125. subprocess.call(["open", "-a", "Preview.app", path])
  126. executable = sys.executable or shutil.which("python3")
  127. if executable:
  128. subprocess.Popen(
  129. [
  130. executable,
  131. "-c",
  132. "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
  133. path,
  134. ]
  135. )
  136. return 1
  137. if sys.platform == "darwin":
  138. register(MacViewer)
  139. class UnixViewer(Viewer):
  140. format = "PNG"
  141. options = {"compress_level": 1, "save_all": True}
  142. def get_command(self, file, **options):
  143. command = self.get_command_ex(file, **options)[0]
  144. return f"({command} {quote(file)}"
  145. class XDGViewer(UnixViewer):
  146. """
  147. The freedesktop.org ``xdg-open`` command.
  148. """
  149. def get_command_ex(self, file, **options):
  150. command = executable = "xdg-open"
  151. return command, executable
  152. def show_file(self, path, **options):
  153. """
  154. Display given file.
  155. """
  156. subprocess.Popen(["xdg-open", path])
  157. return 1
  158. class DisplayViewer(UnixViewer):
  159. """
  160. The ImageMagick ``display`` command.
  161. This viewer supports the ``title`` parameter.
  162. """
  163. def get_command_ex(self, file, title=None, **options):
  164. command = executable = "display"
  165. if title:
  166. command += f" -title {quote(title)}"
  167. return command, executable
  168. def show_file(self, path, **options):
  169. """
  170. Display given file.
  171. """
  172. args = ["display"]
  173. title = options.get("title")
  174. if title:
  175. args += ["-title", title]
  176. args.append(path)
  177. subprocess.Popen(args)
  178. return 1
  179. class GmDisplayViewer(UnixViewer):
  180. """The GraphicsMagick ``gm display`` command."""
  181. def get_command_ex(self, file, **options):
  182. executable = "gm"
  183. command = "gm display"
  184. return command, executable
  185. def show_file(self, path, **options):
  186. """
  187. Display given file.
  188. """
  189. subprocess.Popen(["gm", "display", path])
  190. return 1
  191. class EogViewer(UnixViewer):
  192. """The GNOME Image Viewer ``eog`` command."""
  193. def get_command_ex(self, file, **options):
  194. executable = "eog"
  195. command = "eog -n"
  196. return command, executable
  197. def show_file(self, path, **options):
  198. """
  199. Display given file.
  200. """
  201. subprocess.Popen(["eog", "-n", path])
  202. return 1
  203. class XVViewer(UnixViewer):
  204. """
  205. The X Viewer ``xv`` command.
  206. This viewer supports the ``title`` parameter.
  207. """
  208. def get_command_ex(self, file, title=None, **options):
  209. # note: xv is pretty outdated. most modern systems have
  210. # imagemagick's display command instead.
  211. command = executable = "xv"
  212. if title:
  213. command += f" -name {quote(title)}"
  214. return command, executable
  215. def show_file(self, path, **options):
  216. """
  217. Display given file.
  218. """
  219. args = ["xv"]
  220. title = options.get("title")
  221. if title:
  222. args += ["-name", title]
  223. args.append(path)
  224. subprocess.Popen(args)
  225. return 1
  226. if sys.platform not in ("win32", "darwin"): # unixoids
  227. if shutil.which("xdg-open"):
  228. register(XDGViewer)
  229. if shutil.which("display"):
  230. register(DisplayViewer)
  231. if shutil.which("gm"):
  232. register(GmDisplayViewer)
  233. if shutil.which("eog"):
  234. register(EogViewer)
  235. if shutil.which("xv"):
  236. register(XVViewer)
  237. class IPythonViewer(Viewer):
  238. """The viewer for IPython frontends."""
  239. def show_image(self, image, **options):
  240. ipython_display(image)
  241. return 1
  242. try:
  243. from IPython.display import display as ipython_display
  244. except ImportError:
  245. pass
  246. else:
  247. register(IPythonViewer)
  248. if __name__ == "__main__":
  249. if len(sys.argv) < 2:
  250. print("Syntax: python3 ImageShow.py imagefile [title]")
  251. sys.exit()
  252. with Image.open(sys.argv[1]) as im:
  253. print(show(im, *sys.argv[2:]))