SgiImagePlugin.py 5.9 KB

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