From 6ee41897e277a6e05f3673255b21333d7279d9fa Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 26 Jun 2024 07:19:44 +1000 Subject: [PATCH] Added dedicated unpacker for inverted alpha --- src/PIL/TgaImagePlugin.py | 14 +++++--------- src/libImaging/Unpack.c | 18 +++++++++++++++++- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/PIL/TgaImagePlugin.py b/src/PIL/TgaImagePlugin.py index c41b31d68..39104aece 100644 --- a/src/PIL/TgaImagePlugin.py +++ b/src/PIL/TgaImagePlugin.py @@ -36,7 +36,7 @@ MODES = { (3, 1): "1", (3, 8): "L", (3, 16): "LA", - (2, 16): "BGRA;15", + (2, 16): "BGRA;15Z", (2, 24): "BGR", (2, 32): "BGRA", } @@ -87,9 +87,7 @@ class TgaImageFile(ImageFile.ImageFile): 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) @@ -117,11 +115,9 @@ class TgaImageFile(ImageFile.ImageFile): # 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( diff --git a/src/libImaging/Unpack.c b/src/libImaging/Unpack.c index 063bcbbcc..eaa4374e3 100644 --- a/src/libImaging/Unpack.c +++ b/src/libImaging/Unpack.c @@ -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; @@ -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 */ @@ -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},