TgaImagePlugin.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # TGA file handling
  6. #
  7. # History:
  8. # 95-09-01 fl created (reads 24-bit files only)
  9. # 97-01-04 fl support more TGA versions, including compressed images
  10. # 98-07-04 fl fixed orientation and alpha layer bugs
  11. # 98-09-11 fl fixed orientation for runlength decoder
  12. #
  13. # Copyright (c) Secret Labs AB 1997-98.
  14. # Copyright (c) Fredrik Lundh 1995-97.
  15. #
  16. # See the README file for information on usage and redistribution.
  17. #
  18. import warnings
  19. from . import Image, ImageFile, ImagePalette
  20. from ._binary import i16le as i16
  21. from ._binary import o8
  22. from ._binary import o16le as o16
  23. #
  24. # --------------------------------------------------------------------
  25. # Read RGA file
  26. MODES = {
  27. # map imagetype/depth to rawmode
  28. (1, 8): "P",
  29. (3, 1): "1",
  30. (3, 8): "L",
  31. (3, 16): "LA",
  32. (2, 16): "BGR;5",
  33. (2, 24): "BGR",
  34. (2, 32): "BGRA",
  35. }
  36. ##
  37. # Image plugin for Targa files.
  38. class TgaImageFile(ImageFile.ImageFile):
  39. format = "TGA"
  40. format_description = "Targa"
  41. def _open(self):
  42. # process header
  43. s = self.fp.read(18)
  44. id_len = s[0]
  45. colormaptype = s[1]
  46. imagetype = s[2]
  47. depth = s[16]
  48. flags = s[17]
  49. self._size = i16(s, 12), i16(s, 14)
  50. # validate header fields
  51. if (
  52. colormaptype not in (0, 1)
  53. or self.size[0] <= 0
  54. or self.size[1] <= 0
  55. or depth not in (1, 8, 16, 24, 32)
  56. ):
  57. msg = "not a TGA file"
  58. raise SyntaxError(msg)
  59. # image mode
  60. if imagetype in (3, 11):
  61. self._mode = "L"
  62. if depth == 1:
  63. self._mode = "1" # ???
  64. elif depth == 16:
  65. self._mode = "LA"
  66. elif imagetype in (1, 9):
  67. self._mode = "P"
  68. elif imagetype in (2, 10):
  69. self._mode = "RGB"
  70. if depth == 32:
  71. self._mode = "RGBA"
  72. else:
  73. msg = "unknown TGA mode"
  74. raise SyntaxError(msg)
  75. # orientation
  76. orientation = flags & 0x30
  77. self._flip_horizontally = orientation in [0x10, 0x30]
  78. if orientation in [0x20, 0x30]:
  79. orientation = 1
  80. elif orientation in [0, 0x10]:
  81. orientation = -1
  82. else:
  83. msg = "unknown TGA orientation"
  84. raise SyntaxError(msg)
  85. self.info["orientation"] = orientation
  86. if imagetype & 8:
  87. self.info["compression"] = "tga_rle"
  88. if id_len:
  89. self.info["id_section"] = self.fp.read(id_len)
  90. if colormaptype:
  91. # read palette
  92. start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]
  93. if mapdepth == 16:
  94. self.palette = ImagePalette.raw(
  95. "BGR;15", b"\0" * 2 * start + self.fp.read(2 * size)
  96. )
  97. elif mapdepth == 24:
  98. self.palette = ImagePalette.raw(
  99. "BGR", b"\0" * 3 * start + self.fp.read(3 * size)
  100. )
  101. elif mapdepth == 32:
  102. self.palette = ImagePalette.raw(
  103. "BGRA", b"\0" * 4 * start + self.fp.read(4 * size)
  104. )
  105. # setup tile descriptor
  106. try:
  107. rawmode = MODES[(imagetype & 7, depth)]
  108. if imagetype & 8:
  109. # compressed
  110. self.tile = [
  111. (
  112. "tga_rle",
  113. (0, 0) + self.size,
  114. self.fp.tell(),
  115. (rawmode, orientation, depth),
  116. )
  117. ]
  118. else:
  119. self.tile = [
  120. (
  121. "raw",
  122. (0, 0) + self.size,
  123. self.fp.tell(),
  124. (rawmode, 0, orientation),
  125. )
  126. ]
  127. except KeyError:
  128. pass # cannot decode
  129. def load_end(self):
  130. if self._flip_horizontally:
  131. self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
  132. #
  133. # --------------------------------------------------------------------
  134. # Write TGA file
  135. SAVE = {
  136. "1": ("1", 1, 0, 3),
  137. "L": ("L", 8, 0, 3),
  138. "LA": ("LA", 16, 0, 3),
  139. "P": ("P", 8, 1, 1),
  140. "RGB": ("BGR", 24, 0, 2),
  141. "RGBA": ("BGRA", 32, 0, 2),
  142. }
  143. def _save(im, fp, filename):
  144. try:
  145. rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
  146. except KeyError as e:
  147. msg = f"cannot write mode {im.mode} as TGA"
  148. raise OSError(msg) from e
  149. if "rle" in im.encoderinfo:
  150. rle = im.encoderinfo["rle"]
  151. else:
  152. compression = im.encoderinfo.get("compression", im.info.get("compression"))
  153. rle = compression == "tga_rle"
  154. if rle:
  155. imagetype += 8
  156. id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))
  157. id_len = len(id_section)
  158. if id_len > 255:
  159. id_len = 255
  160. id_section = id_section[:255]
  161. warnings.warn("id_section has been trimmed to 255 characters")
  162. if colormaptype:
  163. palette = im.im.getpalette("RGB", "BGR")
  164. colormaplength, colormapentry = len(palette) // 3, 24
  165. else:
  166. colormaplength, colormapentry = 0, 0
  167. if im.mode in ("LA", "RGBA"):
  168. flags = 8
  169. else:
  170. flags = 0
  171. orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1))
  172. if orientation > 0:
  173. flags = flags | 0x20
  174. fp.write(
  175. o8(id_len)
  176. + o8(colormaptype)
  177. + o8(imagetype)
  178. + o16(0) # colormapfirst
  179. + o16(colormaplength)
  180. + o8(colormapentry)
  181. + o16(0)
  182. + o16(0)
  183. + o16(im.size[0])
  184. + o16(im.size[1])
  185. + o8(bits)
  186. + o8(flags)
  187. )
  188. if id_section:
  189. fp.write(id_section)
  190. if colormaptype:
  191. fp.write(palette)
  192. if rle:
  193. ImageFile._save(
  194. im, fp, [("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))]
  195. )
  196. else:
  197. ImageFile._save(
  198. im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))]
  199. )
  200. # write targa version 2 footer
  201. fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")
  202. #
  203. # --------------------------------------------------------------------
  204. # Registry
  205. Image.register_open(TgaImageFile.format, TgaImageFile)
  206. Image.register_save(TgaImageFile.format, _save)
  207. Image.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"])
  208. Image.register_mime(TgaImageFile.format, "image/x-tga")