RGB to Hex Conversion with Python

0
430

In CSS we use three ways to specify the color in the color property, first one using the name second using the hex values and third using the rgb values, now what basically these rgb and hex values are, let’s see.

RGB Values

The RGB color model is an additive color model in which red, green and blue light are added together in various ways to reproduce a broad array of colors. Name of the model comes from the initials of the three additive primary colors, red, green and blue.(Source)

Hex Values

A hex triplet is a six-digit, three-byte hexadecimal number used in HTML, CSS, SVG, and other computing applications to represent colors. The bytes represent the red, green and blue components of the color. One byte represents a number in the range 00 to FF (in hexadecimal notation), or 0 to 255 in decimal notation. This represents the least (0) to the most (255) intensity of each of the color components. Thus web colors specify colors in the True Color (24-bit RGB) color scheme. The hex triplet is formed by concatenating three bytes in hexadecimal notation, in the following order:

Byte 1: red value (color type red)
2: green value (color type green)
3: blue value (color type blue) (Source)

Let’s see an example on both of them

Now we know what rgb and hex are and dont worry this article in not on CSS
In this article we will learn how to convert rgb to hex and hex to rgb by writing a python code for it.

For this we are going to create two python functions

  • hex2rgb() : To convert rgb to hex
  • rgb2hex() : To convert hex to rgb

Let’s create our first function

In the above function we are taking three parameters r, g, b and formatting each of the value into hexadecimal format and adding a ‘#’ before all the three values and storing the string into a variable hex and then the function returns the hex.

Maybe the second line is a bit confusing for you guys but let me explain it. We are map() function, map basically implements a certain function to all the items present in a list. In the above map() function we are applying the ord() function to all the items, the ord() function takes a string and returns an int representing the unicode code point of the character. The tuple() is used to represent the data in the form of a tuple.

Now implement these functions and write a full code for our RGB2HEX convertor

Output:

rgb to hex conversion in python

Thank you for reading.

Suggest

Complete Python Masterclass

Python for Beginners: from zero to hero in Python

Programming with Python: Hands-On Introduction for Beginners 

LEAVE A REPLY

Please enter your comment!
Please enter your name here