TgaImagePlugin.py 7.9 KB

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