ImageShow.py 9.8 KB

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