Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set all transparent colors to be equal in quantize() #5282

Merged
merged 1 commit into from Mar 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions Tests/test_image_quantize.py
Expand Up @@ -74,3 +74,13 @@ def test_quantize_dither_diff():
nodither = image.quantize(dither=0, palette=palette)

assert dither.tobytes() != nodither.tobytes()


def test_transparent_colors_equal():
im = Image.new("RGBA", (1, 2), (0, 0, 0, 0))
px = im.load()
px[0, 1] = (255, 255, 255, 0)

converted = im.quantize()
converted_px = converted.load()
assert converted_px[0, 0] == converted_px[0, 1]
23 changes: 17 additions & 6 deletions src/libImaging/Quant.c
Expand Up @@ -1688,9 +1688,26 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans) {
} else if (!strcmp(im->mode, "RGB") || !strcmp(im->mode, "RGBA")) {
/* true colour */

withAlpha = !strcmp(im->mode, "RGBA");
int transparency = 0;
unsigned char r, g, b;
for (i = y = 0; y < im->ysize; y++) {
for (x = 0; x < im->xsize; x++, i++) {
p[i].v = im->image32[y][x];
if (withAlpha && p[i].c.a == 0) {
if (transparency == 0) {
transparency = 1;
r = p[i].c.r;
g = p[i].c.g;
b = p[i].c.b;
} else {
/* Set all subsequent transparent pixels
to the same colour as the first */
p[i].c.r = r;
p[i].c.g = g;
p[i].c.b = b;
}
}
}
}

Expand Down Expand Up @@ -1725,9 +1742,6 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans) {
kmeans);
break;
case 2:
if (!strcmp(im->mode, "RGBA")) {
withAlpha = 1;
}
result = quantize_octree(
p,
im->xsize * im->ysize,
Expand All @@ -1739,9 +1753,6 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans) {
break;
case 3:
#ifdef HAVE_LIBIMAGEQUANT
if (!strcmp(im->mode, "RGBA")) {
withAlpha = 1;
}
result = quantize_pngquant(
p,
im->xsize,
Expand Down