TgaImagePlugin.py 6.8 KB

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