Wednesday, April 24, 2024
STEM

How to get exact color values and convert them

In this post, I’ll show you how to get exact RGB colors from an image and then freely convert them to Hex, and from Hex to RGB depending on your needs, whether it’s for CSS or for your application interface.

Being a 12th man of the Seattle Seahawks, I’ll naturally start with the Seahawks logo. There are two main variations of the modern Seahawks logo as shown below. They’re composed of “Seahawks Blue”, “Seahawks Green”, Gray, Slateblue, and white.

If you search online, you’ll get all sorts of cliparts and images made by various fans and designers—which vary slightly in colors. Both of these designs are generally correct, but various images from various sources have slightly different color variations especially in the Seahawks Blue, Seahawks Green, and Slateblue colors. That begs the question: What colors are accurate?

Accordingly to official recordfs, Seahawks Blue (dark navy blue) color code is #002244 and Seahawks Green (bright green) is #69BE28. The Slateblue although not officially defined is usually #2c587d and the gray section should be a1a8b0.

So, if you get an image from the internet, you can verify and even edit the colors to the proper colors yourself. Here’s how without using any other tools other than what’s already in your Windows OS. The real colors, which I had to correct according to the above colors should look like this and I have labelled the colors for each section of the logo:

After you download an image, open it in MSPaint. Then use the eyedropper tool to get the color of an area of interest, then press ‘Edit colors’ button to open the color pallete. The color of the chosen pixel will show as RGB. That’s it…very simple! See the image below with highlighted UI controls in MSPaint.

Now that you have the color dialog open, you can enter the new values for R, G, B according to the spec and press OK. Then that tile of color will appear in the Colors set of tiles in the main window. Click that and use the Bucket tool (right above eyedropper tool) to fill in the section with the correct color, or if the area is not contained, then use brush to select the area carefully. Repeat for every color that you want to change, and save the image.

But “wait…” you say, “we do not know the RGB values! You only shared the official hex colors and MSPaint takes RGB.” Yes, you are correct…which takes us to the next section.

Now we have the exact colors we want in the image, I’ll show you how you can convert any given color to the other most common formats used today. For example, if you’re given RGB values, but you want to use its Hex values with your CSS or application, you need to convert it to Hex accurately. And if you know the Hex colors, but you don’t know the RGB values (like in the example above), you can convert them to RGB values.

HEX->RGB conversion code:

So, we want the RGB colors for the Seahaws Blue hex color #002244 in this example.

First, we will allow user/you to enter the hex value as a string WITH or WITHOUT ‘#‘ prefix. Then we should ensure that it’s in correct format and contains a valid hex string. To do this, we can use the built-in Regular Expression module in Python.

We also need to make sure to remove any leading or trailing space characters (which happens quite a bit when pasting inputs), otherwise, the math conversion will fail.

Next, we check (line #7 in image below) if RegEx returned True on that match, if it did, we know it’s a valid input. But before we apply the conversion math, we have to ensure that there are no other non-numeric characters left in the string by checking for ‘#’ which is a common and required prefix for hex codes. In this case, we want to remove it if it exists and then do the conversion. See lines #10 ,11.

Finally, we convert the cleaned up string containing hex value into a single integer using base 16 because, we’re dealing with hex based input (line #14) and we’re converting to a valid integer in base 10 using int().

This block of code is shown below.

Ok, we are about halfway there. So far, we have a integer value from the hex code stored in variable hex_value. Now we need to break up this integer into R, G, B chunks where each value will be up to maximum value of integer 255. The way to do this is by bitwise operators such as Shift and AND. The block of code is below with explanation below.

First, we shift the bits of hex_value 16 positions to the right, effectively discarding the green and blue components of the color value and leaving us only with the red component. Then the & operator takes the result of the right shift operation and performs a bitwise AND with the value 0xff (255 in decimal). This causes the extraction of the lowest 8 bits of the shifted value, which together represent the red component of the color value. Next, we right-shift by 8 bits and do the same as above to extract green component and so on until the final red value. Why 16 bits, and then 8 bits? Because the hexadecimal color value we are working with is a 24-bit value.

After lines #22..24, we have integer values stored in variables: red, green, blue. We then reformat the integers (if we want to) to a string formatted as “RGB(red,green,blue)” to output on screen/console.

So, if entered the Seahawks Blue color #002244 as input, we get RGB(0,34,68) as output— which looks like the image below if we draw a circle and fill it with that color (more on the drawing part soon).

Let’s look that the conversion method the other way now.

RGB->HEX conversion code:

Define a function that takes a tuple of RGB colors as an argument, unpack the tuple, and reformat each of R, G, B into Hex numbers and return that string as “#xxxxxx” where x is a hex number. Here’s the code for the function:

To call it from another part of your program such as main driver:

rgb_color = (105,190,40) # this is RGB code for Seahawks Green

hex_color = rgb_to_hex(rgb_color) # passing the values as R,G,B tuple

print(hex_color)

And you will get: #69BE28 — which matches with the Seahawks Green hex code we saw above.

In this example, for simplicity, we are passing hardcoded values to our function. For more practical purposes, you want to get input from users for each of R, G, B (three input() calls) and do validation for each entry before you try to reformat to hex or reformatting will obviously fail. The validation should be that each value must be between 0 and 255 inclusive. So, something like:

if r < 0 or r > 255 or g < 0 or g > 255 or b < 0 or b > 255:
print("Invalid RGB values.")

Take it farther (Painting with the converted color):

To take it farther, after you get the hex value, why not use that color to paint a geometric shape with that color to show the user/yourself along with the converted code?

This can be quickly done using turtle library in Python as shown below in a Turtle window:

Let’s take it even one step farther! (Clipboard)

Why not also put the converted color code into the clipboard? That way, if you’re working on a code editor, you can just do Ctrl-V to paste the color code without having to manually retype! That’s even more useful. You can do that using pyperclip module and its copy() method.

I won’t go into the turtle or clipboard specific code here today to keep this blog on topic of color conversions, but if you’re interested in turtle samples, search for “turtle” on this site.

If we draw all key four colors in Turtle animation, they look like this:

Hope you had fun with this.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top