ImageShow.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. pyinstaller = getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS")
  142. executable = (not pyinstaller and sys.executable) or shutil.which("python3")
  143. if executable:
  144. subprocess.Popen(
  145. [
  146. executable,
  147. "-c",
  148. "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
  149. path,
  150. ]
  151. )
  152. return 1
  153. if sys.platform == "darwin":
  154. register(MacViewer)
  155. class UnixViewer(abc.ABC, Viewer):
  156. format = "PNG"
  157. options = {"compress_level": 1, "save_all": True}
  158. @abc.abstractmethod
  159. def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
  160. pass
  161. def get_command(self, file: str, **options: Any) -> str:
  162. command = self.get_command_ex(file, **options)[0]
  163. return f"{command} {quote(file)}"
  164. class XDGViewer(UnixViewer):
  165. """
  166. The freedesktop.org ``xdg-open`` command.
  167. """
  168. def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
  169. command = executable = "xdg-open"
  170. return command, executable
  171. def show_file(self, path: str, **options: Any) -> int:
  172. """
  173. Display given file.
  174. """
  175. if not os.path.exists(path):
  176. raise FileNotFoundError
  177. subprocess.Popen(["xdg-open", path])
  178. return 1
  179. class DisplayViewer(UnixViewer):
  180. """
  181. The ImageMagick ``display`` command.
  182. This viewer supports the ``title`` parameter.
  183. """
  184. def get_command_ex(
  185. self, file: str, title: str | None = None, **options: Any
  186. ) -> tuple[str, str]:
  187. command = executable = "display"
  188. if title:
  189. command += f" -title {quote(title)}"
  190. return command, executable
  191. def show_file(self, path: str, **options: Any) -> int:
  192. """
  193. Display given file.
  194. """
  195. if not os.path.exists(path):
  196. raise FileNotFoundError
  197. args = ["display"]
  198. title = options.get("title")
  199. if title:
  200. args += ["-title", title]
  201. args.append(path)
  202. subprocess.Popen(args)
  203. return 1
  204. class GmDisplayViewer(UnixViewer):
  205. """The GraphicsMagick ``gm display`` command."""
  206. def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
  207. executable = "gm"
  208. command = "gm display"
  209. return command, executable
  210. def show_file(self, path: str, **options: Any) -> int:
  211. """
  212. Display given file.
  213. """
  214. if not os.path.exists(path):
  215. raise FileNotFoundError
  216. subprocess.Popen(["gm", "display", path])
  217. return 1
  218. class EogViewer(UnixViewer):
  219. """The GNOME Image Viewer ``eog`` command."""
  220. def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
  221. executable = "eog"
  222. command = "eog -n"
  223. return command, executable
  224. def show_file(self, path: str, **options: Any) -> int:
  225. """
  226. Display given file.
  227. """
  228. if not os.path.exists(path):
  229. raise FileNotFoundError
  230. subprocess.Popen(["eog", "-n", path])
  231. return 1
  232. class XVViewer(UnixViewer):
  233. """
  234. The X Viewer ``xv`` command.
  235. This viewer supports the ``title`` parameter.
  236. """
  237. def get_command_ex(
  238. self, file: str, title: str | None = None, **options: Any
  239. ) -> tuple[str, str]:
  240. # note: xv is pretty outdated. most modern systems have
  241. # imagemagick's display command instead.
  242. command = executable = "xv"
  243. if title:
  244. command += f" -name {quote(title)}"
  245. return command, executable
  246. def show_file(self, path: str, **options: Any) -> int:
  247. """
  248. Display given file.
  249. """
  250. if not os.path.exists(path):
  251. raise FileNotFoundError
  252. args = ["xv"]
  253. title = options.get("title")
  254. if title:
  255. args += ["-name", title]
  256. args.append(path)
  257. subprocess.Popen(args)
  258. return 1
  259. if sys.platform not in ("win32", "darwin"): # unixoids
  260. if shutil.which("xdg-open"):
  261. register(XDGViewer)
  262. if shutil.which("display"):
  263. register(DisplayViewer)
  264. if shutil.which("gm"):
  265. register(GmDisplayViewer)
  266. if shutil.which("eog"):
  267. register(EogViewer)
  268. if shutil.which("xv"):
  269. register(XVViewer)
  270. class IPythonViewer(Viewer):
  271. """The viewer for IPython frontends."""
  272. def show_image(self, image: Image.Image, **options: Any) -> int:
  273. ipython_display(image)
  274. return 1
  275. try:
  276. from IPython.display import display as ipython_display
  277. except ImportError:
  278. pass
  279. else:
  280. register(IPythonViewer)
  281. if __name__ == "__main__":
  282. if len(sys.argv) < 2:
  283. print("Syntax: python3 ImageShow.py imagefile [title]")
  284. sys.exit()
  285. with Image.open(sys.argv[1]) as im:
  286. print(show(im, *sys.argv[2:]))