SgiImagePlugin.py 6.0 KB

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