Team Ai
Datasetpublic

codekingpro/portable-devtools

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