ImageShow.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. import tempfile
  19. from shlex import quote
  20. from PIL import Image
  21. _viewers = []
  22. def register(viewer, order=1):
  23. """
  24. The :py:func:`register` function is used to register additional viewers.
  25. :param viewer: The viewer to be registered.
  26. :param order:
  27. Zero or a negative integer to prepend this viewer to the list,
  28. a positive integer to append it.
  29. """
  30. try:
  31. if issubclass(viewer, Viewer):
  32. viewer = viewer()
  33. except TypeError:
  34. pass # raised if viewer wasn't a class
  35. if order > 0:
  36. _viewers.append(viewer)
  37. else:
  38. _viewers.insert(0, viewer)
  39. def show(image, title=None, **options):
  40. r"""
  41. Display a given image.
  42. :param image: An image object.
  43. :param title: Optional title. Not all viewers can display the title.
  44. :param \**options: Additional viewer options.
  45. :returns: ``True`` if a suitable viewer was found, ``False`` otherwise.
  46. """
  47. for viewer in _viewers:
  48. if viewer.show(image, title=title, **options):
  49. return 1
  50. return 0
  51. class Viewer:
  52. """Base class for viewers."""
  53. # main api
  54. def show(self, image, **options):
  55. """
  56. The main function for displaying an image.
  57. Converts the given image to the target format and displays it.
  58. """
  59. # save temporary image to disk
  60. if not (
  61. image.mode in ("1", "RGBA")
  62. or (self.format == "PNG" and image.mode in ("I;16", "LA"))
  63. ):
  64. base = Image.getmodebase(image.mode)
  65. if image.mode != base:
  66. image = image.convert(base)
  67. return self.show_image(image, **options)
  68. # hook methods
  69. format = None
  70. """The format to convert the image into."""
  71. options = {}
  72. """Additional options used to convert the image."""
  73. def get_format(self, image):
  74. """Return format name, or ``None`` to save as PGM/PPM."""
  75. return self.format
  76. def get_command(self, file, **options):
  77. """
  78. Returns the command used to display the file.
  79. Not implemented in the base class.
  80. """
  81. raise NotImplementedError
  82. def save_image(self, image):
  83. """Save to temporary file and return filename."""
  84. return image._dump(format=self.get_format(image), **self.options)
  85. def show_image(self, image, **options):
  86. """Display the given image."""
  87. return self.show_file(self.save_image(image), **options)
  88. def show_file(self, file, **options):
  89. """Display the given file."""
  90. os.system(self.get_command(file, **options))
  91. return 1
  92. # --------------------------------------------------------------------
  93. class WindowsViewer(Viewer):
  94. """The default viewer on Windows is the default system application for PNG files."""
  95. format = "PNG"
  96. options = {"compress_level": 1}
  97. def get_command(self, file, **options):
  98. return (
  99. f'start "Pillow" /WAIT "{file}" '
  100. "&& ping -n 2 127.0.0.1 >NUL "
  101. f'&& del /f "{file}"'
  102. )
  103. if sys.platform == "win32":
  104. register(WindowsViewer)
  105. class MacViewer(Viewer):
  106. """The default viewer on MacOS using ``Preview.app``."""
  107. format = "PNG"
  108. options = {"compress_level": 1}
  109. def get_command(self, file, **options):
  110. # on darwin open returns immediately resulting in the temp
  111. # file removal while app is opening
  112. command = "open -a Preview.app"
  113. command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
  114. return command
  115. def show_file(self, file, **options):
  116. """Display given file"""
  117. fd, path = tempfile.mkstemp()
  118. with os.fdopen(fd, "w") as f:
  119. f.write(file)
  120. with open(path) as f:
  121. subprocess.Popen(
  122. ["im=$(cat); open -a Preview.app $im; sleep 20; rm -f $im"],
  123. shell=True,
  124. stdin=f,
  125. )
  126. os.remove(path)
  127. return 1
  128. if sys.platform == "darwin":
  129. register(MacViewer)
  130. class UnixViewer(Viewer):
  131. format = "PNG"
  132. options = {"compress_level": 1}
  133. def get_command(self, file, **options):
  134. command = self.get_command_ex(file, **options)[0]
  135. return f"({command} {quote(file)}; rm -f {quote(file)})&"
  136. def show_file(self, file, **options):
  137. """Display given file"""
  138. fd, path = tempfile.mkstemp()
  139. with os.fdopen(fd, "w") as f:
  140. f.write(file)
  141. with open(path) as f:
  142. command = self.get_command_ex(file, **options)[0]
  143. subprocess.Popen(
  144. ["im=$(cat);" + command + " $im; rm -f $im"], shell=True, stdin=f
  145. )
  146. os.remove(path)
  147. return 1
  148. class DisplayViewer(UnixViewer):
  149. """The ImageMagick ``display`` command."""
  150. def get_command_ex(self, file, **options):
  151. command = executable = "display"
  152. return command, executable
  153. class EogViewer(UnixViewer):
  154. """The GNOME Image Viewer ``eog`` command."""
  155. def get_command_ex(self, file, **options):
  156. command = executable = "eog"
  157. return command, executable
  158. class XVViewer(UnixViewer):
  159. """
  160. The X Viewer ``xv`` command.
  161. This viewer supports the ``title`` parameter.
  162. """
  163. def get_command_ex(self, file, title=None, **options):
  164. # note: xv is pretty outdated. most modern systems have
  165. # imagemagick's display command instead.
  166. command = executable = "xv"
  167. if title:
  168. command += f" -name {quote(title)}"
  169. return command, executable
  170. if sys.platform not in ("win32", "darwin"): # unixoids
  171. if shutil.which("display"):
  172. register(DisplayViewer)
  173. if shutil.which("eog"):
  174. register(EogViewer)
  175. if shutil.which("xv"):
  176. register(XVViewer)
  177. if __name__ == "__main__":
  178. if len(sys.argv) < 2:
  179. print("Syntax: python ImageShow.py imagefile [title]")
  180. sys.exit()
  181. with Image.open(sys.argv[1]) as im:
  182. print(show(im, *sys.argv[2:]))