CFLib.org – Common Function Library Project

ClosestWebSafeColor(hexInput)

Last updated November 21, 2001
Download UDF

author

Tony Brandner                                     Tony Brandner

Version: 1 | Requires: ColdFusion 5 | 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:

<cfscript>
/**
* Returns the closest web safe hexadecimal color for a given hexadecimal color.
*
* @param hexInput     
* @return Returns a string.
* @author Tony Brandner (brandner@canada.com)
* @version 1, November 21, 2001
*/

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';
}
}
</cfscript>

Search CFLib.org


Latest Additions

Jose Diaz-Salcedo Jose Diaz-Salcedo added
cfRssFeed
2 day(s) ago

Raymond Compton Raymond Compton added
structBlend
23 day(s) ago

Duncan Duncan added
IsZIPUK
23 day(s) ago

Todd Sharp Todd Sharp added
getTagContentAll
29 day(s) ago

Gerald Guido Gerald Guido added
ListReturnDuplicat...
1 month(s) ago

Created by Raymond Camden / Design by Justin Johnson