TgaImagePlugin.py 7.4 KB

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