ImageShow.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. import os
  15. import shutil
  16. import subprocess
  17. import sys
  18. from shlex import quote
  19. from PIL import Image
  20. from ._deprecate import deprecate
  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. raise NotImplementedError
  85. def save_image(self, image):
  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, **options):
  89. """Display the given image."""
  90. return self.show_file(self.save_image(image), **options)
  91. def show_file(self, path=None, **options):
  92. """
  93. Display given file.
  94. Before Pillow 9.1.0, the first argument was ``file``. This is now deprecated,
  95. and will be removed in Pillow 10.0.0 (2023-07-01). ``path`` should be used
  96. instead.
  97. """
  98. if path is None:
  99. if "file" in options:
  100. deprecate("The 'file' argument", 10, "'path'")
  101. path = options.pop("file")
  102. else:
  103. raise TypeError("Missing required argument: 'path'")
  104. os.system(self.get_command(path, **options))
  105. return 1
  106. # --------------------------------------------------------------------
  107. class WindowsViewer(Viewer):
  108. """The default viewer on Windows is the default system application for PNG files."""
  109. format = "PNG"
  110. options = {"compress_level": 1}
  111. def get_command(self, file, **options):
  112. return (
  113. f'start "Pillow" /WAIT "{file}" '
  114. "&& ping -n 4 127.0.0.1 >NUL "
  115. f'&& del /f "{file}"'
  116. )
  117. if sys.platform == "win32":
  118. register(WindowsViewer)
  119. class MacViewer(Viewer):
  120. """The default viewer on macOS using ``Preview.app``."""
  121. format = "PNG"
  122. options = {"compress_level": 1}
  123. def get_command(self, file, **options):
  124. # on darwin open returns immediately resulting in the temp
  125. # file removal while app is opening
  126. command = "open -a Preview.app"
  127. command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
  128. return command
  129. def show_file(self, path=None, **options):
  130. """
  131. Display given file.
  132. Before Pillow 9.1.0, the first argument was ``file``. This is now deprecated,
  133. and will be removed in Pillow 10.0.0 (2023-07-01). ``path`` should be used
  134. instead.
  135. """
  136. if path is None:
  137. if "file" in options:
  138. deprecate("The 'file' argument", 10, "'path'")
  139. path = options.pop("file")
  140. else:
  141. raise TypeError("Missing required argument: 'path'")
  142. subprocess.call(["open", "-a", "Preview.app", path])
  143. subprocess.Popen(
  144. [
  145. sys.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}
  157. def get_command(self, file, **options):
  158. command = self.get_command_ex(file, **options)[0]
  159. return f"({command} {quote(file)}"
  160. class XDGViewer(UnixViewer):
  161. """
  162. The freedesktop.org ``xdg-open`` command.
  163. """
  164. def get_command_ex(self, file, **options):
  165. command = executable = "xdg-open"
  166. return command, executable
  167. def show_file(self, path=None, **options):
  168. """
  169. Display given file.
  170. Before Pillow 9.1.0, the first argument was ``file``. This is now deprecated,
  171. and will be removed in Pillow 10.0.0 (2023-07-01). ``path`` should be used
  172. instead.
  173. """
  174. if path is None:
  175. if "file" in options:
  176. deprecate("The 'file' argument", 10, "'path'")
  177. path = options.pop("file")
  178. else:
  179. raise TypeError("Missing required argument: 'path'")
  180. subprocess.Popen(["xdg-open", path])
  181. return 1
  182. class DisplayViewer(UnixViewer):
  183. """
  184. The ImageMagick ``display`` command.
  185. This viewer supports the ``title`` parameter.
  186. """
  187. def get_command_ex(self, file, title=None, **options):
  188. command = executable = "display"
  189. if title:
  190. command += f" -title {quote(title)}"
  191. return command, executable
  192. def show_file(self, path=None, **options):
  193. """
  194. Display given file.
  195. Before Pillow 9.1.0, the first argument was ``file``. This is now deprecated,
  196. and ``path`` should be used instead.
  197. """
  198. if path is None:
  199. if "file" in options:
  200. deprecate("The 'file' argument", 10, "'path'")
  201. path = options.pop("file")
  202. else:
  203. raise TypeError("Missing required argument: 'path'")
  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, **options):
  214. executable = "gm"
  215. command = "gm display"
  216. return command, executable
  217. def show_file(self, path=None, **options):
  218. """
  219. Display given file.
  220. Before Pillow 9.1.0, the first argument was ``file``. This is now deprecated,
  221. and ``path`` should be used instead.
  222. """
  223. if path is None:
  224. if "file" in options:
  225. deprecate("The 'file' argument", 10, "'path'")
  226. path = options.pop("file")
  227. else:
  228. raise TypeError("Missing required argument: 'path'")
  229. subprocess.Popen(["gm", "display", path])
  230. return 1
  231. class EogViewer(UnixViewer):
  232. """The GNOME Image Viewer ``eog`` command."""
  233. def get_command_ex(self, file, **options):
  234. executable = "eog"
  235. command = "eog -n"
  236. return command, executable
  237. def show_file(self, path=None, **options):
  238. """
  239. Display given file.
  240. Before Pillow 9.1.0, the first argument was ``file``. This is now deprecated,
  241. and ``path`` should be used instead.
  242. """
  243. if path is None:
  244. if "file" in options:
  245. deprecate("The 'file' argument", 10, "'path'")
  246. path = options.pop("file")
  247. else:
  248. raise TypeError("Missing required argument: 'path'")
  249. subprocess.Popen(["eog", "-n", path])
  250. return 1
  251. class XVViewer(UnixViewer):
  252. """
  253. The X Viewer ``xv`` command.
  254. This viewer supports the ``title`` parameter.
  255. """
  256. def get_command_ex(self, file, title=None, **options):
  257. # note: xv is pretty outdated. most modern systems have
  258. # imagemagick's display command instead.
  259. command = executable = "xv"
  260. if title:
  261. command += f" -name {quote(title)}"
  262. return command, executable
  263. def show_file(self, path=None, **options):
  264. """
  265. Display given file.
  266. Before Pillow 9.1.0, the first argument was ``file``. This is now deprecated,
  267. and ``path`` should be used instead.
  268. """
  269. if path is None:
  270. if "file" in options:
  271. deprecate("The 'file' argument", 10, "'path'")
  272. path = options.pop("file")
  273. else:
  274. raise TypeError("Missing required argument: 'path'")
  275. args = ["xv"]
  276. title = options.get("title")
  277. if title:
  278. args += ["-name", title]
  279. args.append(path)
  280. subprocess.Popen(args)
  281. return 1
  282. if sys.platform not in ("win32", "darwin"): # unixoids
  283. if shutil.which("xdg-open"):
  284. register(XDGViewer)
  285. if shutil.which("display"):
  286. register(DisplayViewer)
  287. if shutil.which("gm"):
  288. register(GmDisplayViewer)
  289. if shutil.which("eog"):
  290. register(EogViewer)
  291. if shutil.which("xv"):
  292. register(XVViewer)
  293. class IPythonViewer(Viewer):
  294. """The viewer for IPython frontends."""
  295. def show_image(self, image, **options):
  296. ipython_display(image)
  297. return 1
  298. try:
  299. from IPython.display import display as ipython_display
  300. except ImportError:
  301. pass
  302. else:
  303. register(IPythonViewer)
  304. if __name__ == "__main__":
  305. if len(sys.argv) < 2:
  306. print("Syntax: python3 ImageShow.py imagefile [title]")
  307. sys.exit()
  308. with Image.open(sys.argv[1]) as im:
  309. print(show(im, *sys.argv[2:]))