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