473,605 Members | 2,652 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to Produce first-pair RGB, Hex Color value from a percent value

dlite922
1,584 Recognized Expert Top Contributor
I spent a couple hours on this and wanted to save someone else a few hours.

This function takes a percentage value and calculates the RGB color. This is useful for a graph or table in which you want the background or some other indicator to change based on the value.

The problem I spent most of my time on was the loss of yellow.

The code is documented and should be easy to understand. Post any questions or modifications to this post.

License: GPL Public

Expand|Select|Wrap|Line Numbers
  1.  
  2. /**
  3. * Example of use of percent2Color function
  4. * @author Dan M 
  5. * @date 06/24/2010
  6. */
  7.  
  8.  
  9. /**
  10. * This function takes a value and returns an RGB color between Red to Yellow to Green in a given spectrum. 
  11. * 50% = FFFF00 
  12. * @param mixed $value required
  13. * @param mixed $brightness value between 1 and 255
  14. * @param mixed $max default 100
  15. * @param mixed $min default 0
  16. * @param mixed $thirdColorHex '00'
  17. */
  18. function percent2Color($value,$brightness = 255, $max = 100,$min = 0, $thirdColorHex = '00')
  19. {       
  20.     // Calculate first and second color (Inverse relationship)
  21.     $first = (1-($value/$max))*$brightness;
  22.     $second = ($value/$max)*$brightness;
  23.  
  24.     // Find the influence of the middle color (yellow if 1st and 2nd are red and green)
  25.     $diff = abs($first-$second);    
  26.     $influence = ($brightness-$diff)/2;     
  27.     $first = intval($first + $influence);
  28.     $second = intval($second + $influence);
  29.  
  30.     // Convert to HEX, format and return
  31.     $firstHex = str_pad(dechex($first),2,0,STR_PAD_LEFT);     
  32.     $secondHex = str_pad(dechex($second),2,0,STR_PAD_LEFT); 
  33.  
  34.     return $firstHex . $secondHex . $thirdColor ; 
  35.  
  36.     // alternatives:
  37.     // return $thirdColorHex . $firstHex . $secondHex; 
  38.     // return $firstHex . $thirdColorHex . $secondHex;
  39.  
  40. }
  41.  
  42.  
The code is bloated to make it easier to understand for beginners. I know I could have cut corners. It also needs some error checking (e.g. brightness must be between 1 and 255).

If you would like to compact it or add to it, go ahead and post the new version back! You can also change the affecting pair from red-green to green-blue or blue-red with a red hue or green hue as alternative if you want.

Cheers,



Dan M.


Example of use:
Expand|Select|Wrap|Line Numbers
  1.  
  2. <html>
  3. <body>
  4. <table width="300px">
  5. <tr><td>Percent</td><td>Color</td></tr>
  6. <?php
  7.  
  8. $example = array(10,40,28,69,100,0,50); 
  9.  
  10. foreach($example as $x)
  11. {
  12.     $color = percent2Color($x,$brightness = 200); 
  13.     echo "<tr><td>$x</td><td style='background-color:#$color'>$color</td>";
  14. }
  15.  
  16. ?>
  17. </table>
  18.  
  19. </body>
  20. </html>
  21. </html>
  22.  
  23.  
Jun 24 '10 #1
1 7982
Markus
6,050 Recognized Expert Expert
Cool stuff, D.
Nov 25 '10 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

2
17411
by: Matt | last post by:
I want to generate text output from XML using XSLT. The question is how to produce a newline? When I produce HTML as output, I have no problems. But when I attempt to produce text, all data is append together. please help. thanks!!
1
2229
by: Grim Reaper | last post by:
I asked this question, earlier, and received an answer that I am not sure about how to do. Basically, I am printing mailing labels with a "Sorting/Grouping" section that groups the label types together. Also, I am using a "Report Header" to show a count of how many total labels that are being printed. Now, my problem is that without the "Report Header", the spacing is perfect. But, when I add the Report Header, it gets shifted...
4
2263
by: wizard_chef | last post by:
I have a database containing info on subscribers to an organization. I have one table with members info in it (name, address, etc.), another table containing orders for membership, (AV materials, etc.), and other ancillary related tables. I need to query my database to find all of the members who paid their dues last year, but did NOT pay this year. Sounds easy, but I can't seem to create a query or queries that does the job. When I...
4
3434
by: WJA | last post by:
I'm probably missing something here but I can't understand the following. When 2 users try to save a record with the same primary key (a number field), the first record saves as expected, but the second does not produce an error. The "Save" button uses "Docmd.Save" to save the record. If I insert "Me.Dirty = False" before "Docmd.Save" an error is produced. Why doesn't "Docmd.Save" produce an error but instead silently fails to save the...
3
2190
by: Eric Davies | last post by:
We've implemented a 5D box data type and have implemented both RTree and GiST access methods under PostgresSQL 7.4 and PostgresSQL 7.4.1. The 5D box internally looks like: struct Box5D{ float minBounds; float maxBounds; }; and so takes up 40 bytes and is of fixed length. The GiST access methods are basically a generalization of the 2D box indexing access methods from Refraction Research's PostGIS.
3
1772
by: Birky | last post by:
I’m looking for suggestions to see if it is possible to produce information in a read only format for my users. I have an event log within an Access table which tracks all the installations within our servers (there are 34 different servers by the way). The users need the ability to query this information by the specific server name. How can I produce this information via an easy interface (report, query, datasheet, etc) which would allow the...
30
2945
by: lovecreatesbea... | last post by:
K&R says the following in the preface to the first edition, "... the C compiler, and ... are written in C." I'm wondering, does it say even the first / original C compiler was written in C?
5
1546
by: Chad Miller | last post by:
Public mLength As Integer Public mChannels As Short Public mSampleRate As Integer Public mDataLength As Integer Public mBitsPerSample As Short Public Sub CreateWaveHeader(ByRef sPath As String) Dim fileNumber As Integer Try
2
7007
bwesenberg
by: bwesenberg | last post by:
I am not sure how to explain this so I will try to the best of my ability. I need to be able to produce 1000 labels from access that are based on consecutive numbers that Access will produce. Here are some of the criteria they are looking for: Need to be able to produce labels on demand – generating at least 1,000 labels at a time. The program will know what the last number used was so when they print the next batch of labels it...
6
4497
by: chazzy69 | last post by:
Im currently using a php script to access a database and use the following lines to produce a backup of a table- $query = "SELECT * INTO OUTFILE 'test.sql' FROM `default_en_listingsdbelements`"; $result = mysql_query($query); Which seems to execute fine and produces no errors except it doesn't actually produce any file. I figured it would produce the file in the same directory as the script or if not in the root directory but...
0
8004
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7934
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8425
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8418
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8071
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
5886
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5445
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3912
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1541
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.