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