CFLib.org – Common Function Library Project

ClosestWebSafeColor(hexInput)

Last updated July 15, 2013

author

Tony Brandner

Version: 1 | Requires: CF5 | Library: UtilityLib

Description:
Takes a hex color in, and returns the closest web safe hexadecimal color. Returns a NULL (empty) string if input hex string is invalid. Thanks to Eric Carlisle (IsWebSafeColor)

Return Values:
Returns a string.

Example:

<CFOUTPUT>
003366, #closestWebSafeColor('003366')#<br>
aabbcc, #closestWebSafeColor('aabbcc')#<br>
112233, #closestWebSafeColor('112233')#<br>
eeffgg, #closestWebSafeColor('eeffgg')#<br>
fffffcc, #closestWebSafeColor('fffffcc')#<br>
##c0c00c, #closestWebSafeColor('##c0c00c')#
</CFOUTPUT>

Parameters:

Name Description Required
hexInput Yes

Full UDF Source:

/**
 * Returns the closest web safe hexadecimal color for a given hexadecimal color.
 * 
 * @param hexInput 	  (Required)
 * @return Returns a string. 
 * @author Tony Brandner (tony@brandners.com) 
 * @version 1, July 15, 2013 
 */
function closestWebSafeColor(hexInput) {
  var cleanHexInput = replace(hexInput,'##','','ALL');
  var hexOutput = '';
  var i = 0;
  if (Len(ReReplace(cleanHexInput, "[0-9abcdefABCDEF]", "","ALL")) eq 0 and Len(cleanHexInput) eq 6) {
    for (i=1; i lte 5; i=i+2) {
      closestMatch = 51 * Round((InputBaseN(mid(cleanHexInput,i,2),16)/51));
      if (closestMatch eq 0) {
        hexOutput = hexOutput & '00';
	} 
      else {
        hexOutput = hexOutput & FormatBaseN(closestMatch,16);
      }
    }
    return hexOutput;
  } 
  else {
    return 'invalid';
  }
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson