TgaImagePlugin.py 6.3 KB

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