SgiImagePlugin.py 6.2 KB

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