SgiImagePlugin.py 6.1 KB

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