TgaImagePlugin.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. (
  117. "tga_rle",
  118. (0, 0) + self.size,
  119. self.fp.tell(),
  120. (rawmode, orientation, depth),
  121. )
  122. ]
  123. else:
  124. self.tile = [
  125. (
  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. assert self.im is not None
  137. self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
  138. #
  139. # --------------------------------------------------------------------
  140. # Write TGA file
  141. SAVE = {
  142. "1": ("1", 1, 0, 3),
  143. "L": ("L", 8, 0, 3),
  144. "LA": ("LA", 16, 0, 3),
  145. "P": ("P", 8, 1, 1),
  146. "RGB": ("BGR", 24, 0, 2),
  147. "RGBA": ("BGRA", 32, 0, 2),
  148. }
  149. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  150. try:
  151. rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
  152. except KeyError as e:
  153. msg = f"cannot write mode {im.mode} as TGA"
  154. raise OSError(msg) from e
  155. if "rle" in im.encoderinfo:
  156. rle = im.encoderinfo["rle"]
  157. else:
  158. compression = im.encoderinfo.get("compression", im.info.get("compression"))
  159. rle = compression == "tga_rle"
  160. if rle:
  161. imagetype += 8
  162. id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))
  163. id_len = len(id_section)
  164. if id_len > 255:
  165. id_len = 255
  166. id_section = id_section[:255]
  167. warnings.warn("id_section has been trimmed to 255 characters")
  168. if colormaptype:
  169. assert im.im is not None
  170. palette = im.im.getpalette("RGB", "BGR")
  171. colormaplength, colormapentry = len(palette) // 3, 24
  172. else:
  173. colormaplength, colormapentry = 0, 0
  174. if im.mode in ("LA", "RGBA"):
  175. flags = 8
  176. else:
  177. flags = 0
  178. orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1))
  179. if orientation > 0:
  180. flags = flags | 0x20
  181. fp.write(
  182. o8(id_len)
  183. + o8(colormaptype)
  184. + o8(imagetype)
  185. + o16(0) # colormapfirst
  186. + o16(colormaplength)
  187. + o8(colormapentry)
  188. + o16(0)
  189. + o16(0)
  190. + o16(im.size[0])
  191. + o16(im.size[1])
  192. + o8(bits)
  193. + o8(flags)
  194. )
  195. if id_section:
  196. fp.write(id_section)
  197. if colormaptype:
  198. fp.write(palette)
  199. if rle:
  200. ImageFile._save(
  201. im, fp, [("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))]
  202. )
  203. else:
  204. ImageFile._save(
  205. im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))]
  206. )
  207. # write targa version 2 footer
  208. fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")
  209. #
  210. # --------------------------------------------------------------------
  211. # Registry
  212. Image.register_open(TgaImageFile.format, TgaImageFile)
  213. Image.register_save(TgaImageFile.format, _save)
  214. Image.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"])
  215. Image.register_mime(TgaImageFile.format, "image/x-tga")