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

Added conversion from RGBa to RGB #6708

Merged
merged 1 commit into from Dec 28, 2022
Merged

Conversation

radarhere
Copy link
Member

@radarhere radarhere commented Oct 31, 2022

Resolves #6706. Alternative to #6707

The new conversion function is just a copy of

static void
rgba2rgbA(UINT8 *out, const UINT8 *in, int xsize) {
int x;
unsigned int alpha;
for (x = 0; x < xsize; x++, in += 4) {
alpha = in[3];
if (alpha == 255 || alpha == 0) {
*out++ = in[0];
*out++ = in[1];
*out++ = in[2];
} else {
*out++ = CLIP8((255 * in[0]) / alpha);
*out++ = CLIP8((255 * in[1]) / alpha);
*out++ = CLIP8((255 * in[2]) / alpha);
}
*out++ = in[3];
}
}

except with the last channel set to 255, as happens in other conversions to RGB.
static void
rgba2rgb(UINT8 *out, const UINT8 *in, int xsize) {
int x;
for (x = 0; x < xsize; x++) {
*out++ = *in++;
*out++ = *in++;
*out++ = *in++;
*out++ = 255;
in++;
}
}

@bigcat88
Copy link
Contributor

Yep, you're right, that's my bad. Good Job! :)

@bigcat88
Copy link
Contributor

but I was always thinking that algorithm for premultiplied alpha is
v[0] = v[0] * (v[3] / 255)

@nulano
Copy link
Contributor

nulano commented Oct 31, 2022

but I was always thinking that algorithm for premultiplied alpha is
v[0] = v[0] * (v[3] / 255)

That is correct. If we denote RGBA as the 8-bit non-premultiplied values and R'G'B'A as the 8-bit premultiplied values, then to get the premultiplied values you calculate R' = (R * A) / 255. (Doing the division after to avoid rounding errors.)

If you want to go back to the non-premultiplied values, you rearrange that equation to get R = (R' * 255) / A.

@bigcat88
Copy link
Contributor

Can this be merged before a new version is released?

@radarhere
Copy link
Member Author

Simply waiting for a review from another maintainer.

There is often more activity just before a release, and this is a relatively simple change, so in my experience I would expect this to make it in.

@hugovk hugovk merged commit 88a81db into python-pillow:main Dec 28, 2022
@radarhere radarhere deleted the rgba2rgb_ branch December 28, 2022 21:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

convert("RGB") fails for RGBa
4 participants