2
# The Python Imaging Library.
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
13
# Copyright (c) Secret Labs AB 1997-98.
14
# Copyright (c) Fredrik Lundh 1995-97.
16
# See the README file for information on usage and redistribution.
22
import Image, ImageFile, ImagePalette
26
# --------------------------------------------------------------------
30
return ord(c[0]) + (ord(c[1])<<8)
33
return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + (ord(c[3])<<24)
37
# map imagetype/depth to rawmode
48
return prefix[0] == "\0"
51
# Image plugin for Targa files.
53
class TgaImageFile(ImageFile.ImageFile):
56
format_description = "Targa"
65
colormaptype = ord(s[1])
72
self.size = i16(s[12:]), i16(s[14:])
74
# validate header fields
75
if id != 0 or colormaptype not in (0, 1) or\
76
self.size[0] <= 0 or self.size[1] <= 0 or\
77
depth not in (1, 8, 16, 24, 32):
78
raise SyntaxError, "not a TGA file"
81
if imagetype in (3, 11):
85
elif imagetype in (1, 9):
87
elif imagetype in (2, 10):
92
raise SyntaxError, "unknown TGA mode"
95
orientation = flags & 0x30
96
if orientation == 0x20:
101
raise SyntaxError, "unknown TGA orientation"
103
self.info["orientation"] = orientation
106
self.info["compression"] = "tga_rle"
110
start, size, mapdepth = i16(s[3:]), i16(s[5:]), i16(s[7:])
112
self.palette = ImagePalette.raw("BGR;16",
113
"\0"*2*start + self.fp.read(2*size))
115
self.palette = ImagePalette.raw("BGR",
116
"\0"*3*start + self.fp.read(3*size))
118
self.palette = ImagePalette.raw("BGRA",
119
"\0"*4*start + self.fp.read(4*size))
121
# setup tile descriptor
123
rawmode = MODES[(imagetype&7, depth)]
126
self.tile = [("tga_rle", (0, 0)+self.size,
127
self.fp.tell(), (rawmode, orientation, depth))]
129
self.tile = [("raw", (0, 0)+self.size,
130
self.fp.tell(), (rawmode, 0, orientation))]
135
# --------------------------------------------------------------------
139
return chr(i&255) + chr(i>>8&255)
142
return chr(i&255) + chr(i>>8&255) + chr(i>>16&255) + chr(i>>24&255)
148
"RGB": ("BGR", 24, 0, 2),
149
"RGBA": ("BGRA", 32, 0, 2),
152
def _save(im, fp, filename, check=0):
155
rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
157
raise IOError("cannot write mode %s as TGA" % im.mode)
163
colormapfirst, colormaplength, colormapentry = 0, 256, 24
165
colormapfirst, colormaplength, colormapentry = 0, 0, 0
167
if im.mode == "RGBA":
172
orientation = im.info.get("orientation", -1)
180
o16(colormaplength) +
190
fp.write(im.im.getpalette("RGB", "BGR"))
192
ImageFile._save(im, fp, [("raw", (0,0)+im.size, 0, (rawmode, 0, orientation))])
195
# --------------------------------------------------------------------
198
Image.register_open("TGA", TgaImageFile, _accept)
199
Image.register_save("TGA", _save)
201
Image.register_extension("TGA", ".tga")