Skip to content

Commit

Permalink
Added dedicated unpacker for inverted alpha
Browse files Browse the repository at this point in the history
  • Loading branch information
radarhere committed Jun 25, 2024
1 parent 4cadf5c commit 6fe3674
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
14 changes: 5 additions & 9 deletions src/PIL/TgaImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
(3, 1): "1",
(3, 8): "L",
(3, 16): "LA",
(2, 16): "BGRA;15",
(2, 16): "BGRA;15Z",
(2, 24): "BGR",
(2, 32): "BGRA",
}
Expand Down Expand Up @@ -87,9 +87,7 @@ def _open(self) -> None:
elif imagetype in (1, 9):
self._mode = "P" if colormaptype else "L"
elif imagetype in (2, 10):
self._mode = "RGB"
if depth == 32:
self._mode = "RGBA"
self._mode = "RGB" if depth == 24 else "RGBA"
else:
msg = "unknown TGA mode"
raise SyntaxError(msg)
Expand Down Expand Up @@ -117,11 +115,9 @@ def _open(self) -> None:
# read palette
start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]
if mapdepth == 16:
colormap = self.fp.read(2 * size)
palette_data = bytearray(2 * start)
for a, b in zip(colormap[::2], colormap[1::2]):
palette_data += bytearray((a, b ^ 128))
self.palette = ImagePalette.raw("BGRA;15", bytes(palette_data))
self.palette = ImagePalette.raw(
"BGRA;15Z", bytes(2 * start) + self.fp.read(2 * size)
)
self.palette.mode = "RGBA"
elif mapdepth == 24:
self.palette = ImagePalette.raw(
Expand Down
18 changes: 17 additions & 1 deletion src/libImaging/Unpack.c
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,21 @@ ImagingUnpackBGRA15(UINT8 *out, const UINT8 *in, int pixels) {
}
}

void
ImagingUnpackBGRA15Z(UINT8 *out, const UINT8 *in, int pixels) {
int i, pixel;
/* RGB, rearranged channels, 5/5/5/1 bits per pixel, inverted alpha */
for (i = 0; i < pixels; i++) {
pixel = in[0] + (in[1] << 8);
out[B] = (pixel & 31) * 255 / 31;
out[G] = ((pixel >> 5) & 31) * 255 / 31;
out[R] = ((pixel >> 10) & 31) * 255 / 31;
out[A] = ~((pixel >> 15) * 255);
out += 4;
in += 2;
}
}

void
ImagingUnpackRGB16(UINT8 *out, const UINT8 *in, int pixels) {
int i, pixel;
Expand Down Expand Up @@ -1538,7 +1553,7 @@ static struct {

/* flags: "I" inverted data; "R" reversed bit order; "B" big
endian byte order (default is little endian); "L" line
interleave, "S" signed, "F" floating point */
interleave, "S" signed, "F" floating point, "Z" inverted alpha */

/* exception: rawmodes "I" and "F" are always native endian byte order */

Expand Down Expand Up @@ -1646,6 +1661,7 @@ static struct {
{"RGBA", "RGBA;L", 32, unpackRGBAL},
{"RGBA", "RGBA;15", 16, ImagingUnpackRGBA15},
{"RGBA", "BGRA;15", 16, ImagingUnpackBGRA15},
{"RGBA", "BGRA;15Z", 16, ImagingUnpackBGRA15Z},
{"RGBA", "RGBA;4B", 16, ImagingUnpackRGBA4B},
{"RGBA", "RGBA;16L", 64, unpackRGBA16L},
{"RGBA", "RGBA;16B", 64, unpackRGBA16B},
Expand Down

0 comments on commit 6fe3674

Please sign in to comment.