I've googled everywhere and can't find any resource or page that goes in to how to accomplish this. Most results just work with rgba() etc.
What I want exactly: To convert a 8-Digit hex
with transparency to a 6-Digit hex
with the transparency applied (assuming a white background).
For example: I have the following colors:
#14C4C1FD
#F25021F4
#FE7162FD
#A259FFFD
#6A9A9C60
#28B8ABBB
#5B9CB931
I want to flatten these colors, so that I get a resulting list of 6-Digit hex codes that reflect the visible color when the transparency is applied. I don't want to just trim the last two digits and remove the transparency.
As mentioned in the image, an algorithm would be great. I am using PowerShell but really I'll take any algorithm in any language and just port it myself.
Direct conversion from the #RRGGBBAA
format to #RRGGBB
is not straightforward. To accomplish this, you must initially transform the #RRGGBBAA
colour format into RGBA
. This involves removing transparency from the colour, and subsequently, you can convert the resulting RGB
values back into the Hex format.
Here is a simple algorithm for your use case in Python:
def rgba_to_rgb(hex_color):
# Assuming a white background, so the background RGB is (255, 255, 255)
background_r, background_g, background_b = 255, 255, 255
# Extract RGBA from hex
r = int(hex_color[1:3], 16)
g = int(hex_color[3:5], 16)
b = int(hex_color[5:7], 16)
a = int(hex_color[7:9], 16) / 255.0 # Convert to a scale of 0 to 1
# Calculate new RGB by blending the original color with the background
new_r = round((1 - a) * background_r + a * r)
new_g = round((1 - a) * background_g + a * g)
new_b = round((1 - a) * background_b + a * b)
# Convert RGB back to hex
return f"#{new_r:02X}{new_g:02X}{new_b:02X}"
# Example usage
colors = [
"#14C4C1FD",
"#F25021F4",
"#FE7162FD",
"#A259FFFD",
"#6A9A9C60",
"#28B8ABBB",
"#5B9CB931",
]
for color in colors:
converted = rgba_to_rgb(color)
print(f"{color} -> {converted}")