ImageShow.py 10 KB

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