SgiImagePlugin.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # SGI image file handling
  6. #
  7. # See "The SGI Image File Format (Draft version 0.97)", Paul Haeberli.
  8. # <ftp://ftp.sgi.com/graphics/SGIIMAGESPEC>
  9. #
  10. #
  11. # History:
  12. # 2017-22-07 mb Add RLE decompression
  13. # 2016-16-10 mb Add save method without compression
  14. # 1995-09-10 fl Created
  15. #
  16. # Copyright (c) 2016 by Mickael Bonfill.
  17. # Copyright (c) 2008 by Karsten Hiddemann.
  18. # Copyright (c) 1997 by Secret Labs AB.
  19. # Copyright (c) 1995 by Fredrik Lundh.
  20. #
  21. # See the README file for information on usage and redistribution.
  22. #
  23. from __future__ import annotations
  24. __lazy_modules__ = {"PIL._binary", "struct"}
  25. import os
  26. import struct
  27. from . import Image, ImageFile
  28. from ._binary import i16be as i16
  29. from ._binary import o8
  30. TYPE_CHECKING = False
  31. if TYPE_CHECKING:
  32. from typing import IO
  33. def _accept(prefix: bytes) -> bool:
  34. return len(prefix) >= 2 and i16(prefix) == 474
  35. MODES = {
  36. (1, 1, 1): "L",
  37. (1, 2, 1): "L",
  38. (2, 1, 1): "L;16B",
  39. (2, 2, 1): "L;16B",
  40. (1, 3, 3): "RGB",
  41. (2, 3, 3): "RGB;16B",
  42. (1, 3, 4): "RGBA",
  43. (2, 3, 4): "RGBA;16B",
  44. }
  45. ##
  46. # Image plugin for SGI images.
  47. class SgiImageFile(ImageFile.ImageFile):
  48. format = "SGI"
  49. format_description = "SGI Image File Format"
  50. def _open(self) -> None:
  51. # HEAD
  52. assert self.fp is not None
  53. headlen = 512
  54. s = self.fp.read(headlen)
  55. if not _accept(s):
  56. msg = "Not an SGI image file"
  57. raise ValueError(msg)
  58. # compression : verbatim or RLE
  59. compression = s[2]
  60. # bpc : 1 or 2 bytes (8bits or 16bits)
  61. bpc = s[3]
  62. # dimension : 1, 2 or 3 (depending on xsize, ysize and zsize)
  63. dimension = i16(s, 4)
  64. # xsize : width
  65. xsize = i16(s, 6)
  66. # ysize : height
  67. ysize = i16(s, 8)
  68. # zsize : channels count
  69. zsize = i16(s, 10)
  70. # determine mode from bits/zsize
  71. try:
  72. rawmode = MODES[(bpc, dimension, zsize)]
  73. except KeyError:
  74. msg = "Unsupported SGI image mode"
  75. raise ValueError(msg)
  76. self._size = xsize, ysize
  77. self._mode = rawmode.split(";")[0]
  78. if self.mode == "RGB":
  79. self.custom_mimetype = "image/rgb"
  80. # orientation -1 : scanlines begins at the bottom-left corner
  81. orientation = -1
  82. # decoder info
  83. if compression == 0:
  84. pagesize = xsize * ysize * bpc
  85. if bpc == 2:
  86. self.tile = [
  87. ImageFile._Tile(
  88. "SGI16",
  89. (0, 0, *self.size),
  90. headlen,
  91. (self.mode, 0, orientation),
  92. )
  93. ]
  94. else:
  95. self.tile = []
  96. offset = headlen
  97. for layer in self.mode:
  98. self.tile.append(
  99. ImageFile._Tile(
  100. "raw", (0, 0, *self.size), offset, (layer, 0, orientation)
  101. )
  102. )
  103. offset += pagesize
  104. elif compression == 1:
  105. self.tile = [
  106. ImageFile._Tile(
  107. "sgi_rle", (0, 0, *self.size), headlen, (rawmode, orientation, bpc)
  108. )
  109. ]
  110. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  111. if im.mode not in {"RGB", "RGBA", "L"}:
  112. msg = "Unsupported SGI image mode"
  113. raise ValueError(msg)
  114. # Get the keyword arguments
  115. info = im.encoderinfo
  116. # Byte-per-pixel precision, 1 = 8bits per pixel
  117. bpc = info.get("bpc", 1)
  118. if bpc not in (1, 2):
  119. msg = "Unsupported number of bytes per pixel"
  120. raise ValueError(msg)
  121. # Flip the image, since the origin of SGI file is the bottom-left corner
  122. orientation = -1
  123. # Define the file as SGI File Format
  124. magic_number = 474
  125. # Run-Length Encoding Compression - Unsupported at this time
  126. rle = 0
  127. # X Dimension = width / Y Dimension = height
  128. x, y = im.size
  129. # Z Dimension: Number of channels
  130. z = len(im.mode)
  131. # Number of dimensions (x,y,z)
  132. if im.mode == "L":
  133. dimension = 1 if y == 1 else 2
  134. else:
  135. dimension = 3
  136. # Minimum Byte value
  137. pinmin = 0
  138. # Maximum Byte value (255 = 8bits per pixel)
  139. pinmax = 255
  140. # Image name (79 characters max, truncated below in write)
  141. img_name = os.path.splitext(os.path.basename(filename))[0]
  142. if isinstance(img_name, str):
  143. img_name = img_name.encode("ascii", "ignore")
  144. # Standard representation of pixel in the file
  145. colormap = 0
  146. fp.write(struct.pack(">h", magic_number))
  147. fp.write(o8(rle))
  148. fp.write(o8(bpc))
  149. fp.write(struct.pack(">H", dimension))
  150. fp.write(struct.pack(">H", x))
  151. fp.write(struct.pack(">H", y))
  152. fp.write(struct.pack(">H", z))
  153. fp.write(struct.pack(">l", pinmin))
  154. fp.write(struct.pack(">l", pinmax))
  155. fp.write(struct.pack("4s", b"")) # dummy
  156. fp.write(struct.pack("79s", img_name)) # truncates to 79 chars
  157. fp.write(struct.pack("s", b"")) # force null byte after img_name
  158. fp.write(struct.pack(">l", colormap))
  159. fp.write(struct.pack("404s", b"")) # dummy
  160. rawmode = "L"
  161. if bpc == 2:
  162. rawmode = "L;16B"
  163. for channel in im.split():
  164. fp.write(channel.tobytes("raw", rawmode, 0, orientation))
  165. if hasattr(fp, "flush"):
  166. fp.flush()
  167. class SGI16Decoder(ImageFile.PyDecoder):
  168. _pulls_fd = True
  169. def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]:
  170. assert self.fd is not None
  171. assert self.im is not None
  172. rawmode, stride, orientation = self.args
  173. pagesize = self.state.xsize * self.state.ysize
  174. zsize = len(self.mode)
  175. self.fd.seek(512)
  176. for band in range(zsize):
  177. channel = Image.new("L", (self.state.xsize, self.state.ysize))
  178. channel.frombytes(
  179. self.fd.read(2 * pagesize), "raw", "L;16B", stride, orientation
  180. )
  181. self.im.putband(channel.im, band)
  182. return -1, 0
  183. #
  184. # registry
  185. Image.register_decoder("SGI16", SGI16Decoder)
  186. Image.register_open(SgiImageFile.format, SgiImageFile, _accept)
  187. Image.register_save(SgiImageFile.format, _save)
  188. Image.register_mime(SgiImageFile.format, "image/sgi")
  189. Image.register_extensions(SgiImageFile.format, [".bw", ".rgb", ".rgba", ".sgi"])
  190. # End of file