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 ImageFile._Tile(
141 "tga_rle",
142 (0, 0) + self.size,
143 self.fp.tell(),
144 (rawmode, orientation, depth),
145 )
146 ]
147 else:
148 self.tile = [
149 ImageFile._Tile(
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 self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
162
163
164#
165# --------------------------------------------------------------------
166# Write TGA file
167
168
169SAVE = {
170 "1": ("1", 1, 0, 3),
171 "L": ("L", 8, 0, 3),
172 "LA": ("LA", 16, 0, 3),
173 "P": ("P", 8, 1, 1),
174 "RGB": ("BGR", 24, 0, 2),
175 "RGBA": ("BGRA", 32, 0, 2),
176}
177
178
179def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
180 try:
181 rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
182 except KeyError as e:
183 msg = f"cannot write mode {im.mode} as TGA"
184 raise OSError(msg) from e
185
186 if "rle" in im.encoderinfo:
187 rle = im.encoderinfo["rle"]
188 else:
189 compression = im.encoderinfo.get("compression", im.info.get("compression"))
190 rle = compression == "tga_rle"
191 if rle:
192 imagetype += 8
193
194 id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))
195 id_len = len(id_section)
196 if id_len > 255:
197 id_len = 255
198 id_section = id_section[:255]
199 warnings.warn("id_section has been trimmed to 255 characters")
200
201 if colormaptype:
202 palette = im.im.getpalette("RGB", "BGR")
203 colormaplength, colormapentry = len(palette) // 3, 24
204 else:
205 colormaplength, colormapentry = 0, 0
206
207 if im.mode in ("LA", "RGBA"):
208 flags = 8
209 else:
210 flags = 0
211
212 orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1))
213 if orientation > 0:
214 flags = flags | 0x20
215
216 fp.write(
217 o8(id_len)
218 + o8(colormaptype)
219 + o8(imagetype)
220 + o16(0) # colormapfirst
221 + o16(colormaplength)
222 + o8(colormapentry)
223 + o16(0)
224 + o16(0)
225 + o16(im.size[0])
226 + o16(im.size[1])
227 + o8(bits)
228 + o8(flags)
229 )
230
231 if id_section:
232 fp.write(id_section)
233
234 if colormaptype:
235 fp.write(palette)
236
237 if rle:
238 ImageFile._save(
239 im,
240 fp,
241 [ImageFile._Tile("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))],
242 )
243 else:
244 ImageFile._save(
245 im,
246 fp,
247 [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))],
248 )
249
250 # write targa version 2 footer
251 fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")
252
253
254#
255# --------------------------------------------------------------------
256# Registry
257
258
259Image.register_open(TgaImageFile.format, TgaImageFile)
260Image.register_save(TgaImageFile.format, _save)
261
262Image.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"])
263
264Image.register_mime(TgaImageFile.format, "image/x-tga")