Is there LaTeX code to convert % based rgb to 0-255 based RGB color codes

colorconvert

I have hundreds of mixed color definitions in my project that use three different color coding styles, e.g. (% based) rgb, (0-255 based) RGB, and (FFFFFF) HTML :

\definecolor{lemon}{rgb}{1.0, 0.97, 0.0}
\definecolor{maize}{rgb}{0.98, 0.93, 0.37}
\definecolor{mustard}{rgb}{1.0, 0.86, 0.35}
\definecolor{ocre}{HTML}{F16723}
\definecolor{Tangerine}{RGB}{253,128,8}

In a housekeeping move, as a way to sort my colors according to their numeric codes, I'm wondering if there might be LaTeX code already out in the ether that I could use to convert the (% based) rgb color definitions to (0-255 based) RGB color definitions, e.g. to convert:

\definecolor{maize}{rgb}{0.98, 0.93, 0.37}

to:

\definecolor{maize}{RGB}{250,237,94}

Ideally, the code would then write out the LaTeX code for the converted colors in (0-255 based) RGB color (LaTeX) code into a text file.

If such LaTeX code exists, I could then use the LaTeX (% based) rgb to (0-255 based) RGB conversion code as a model to create LaTeX code to convert HTML colors TO (0-255 based) RGB colors.

Once all the colors have been converted to (0-255 based) RGB colors, I could then sort all the color definitions numerically by their (0-255 based) RGB colors.

Best Answer

The following example code redefines \definecolor{<colour>}{<model>}{<spec>} so that it can output an updated \definecolor{<colour>}{RGB}{<RGB spec>} to a file called colour.txt (thanks to Figuring out RGB or HEX color from xcolor):

enter image description here

\documentclass{article}

\usepackage{newfile}

\newoutputstream{colourfile}
\openoutputfile{colour.txt}{colourfile}

\usepackage{xcolor}

\let\olddefinecolor\definecolor
\renewcommand{\definecolor}[3]{%
  \olddefinecolor{#1}{#2}{#3}% Original colour definition
  % Taken from: https://tex.stackexchange.com/q/35033/5764
  \extractcolorspec{#1}{\tempcolourspec}% Extract colour specification
  \expandafter\convertcolorspec\tempcolourspec{RGB}\tempcolourspec% Convert colour specification to RGB
  \addtostream{colourfile}{% Write RGB colour specification to file
    \protect\definecolor{#1}{RGB}{\tempcolourspec}%
  }%
}
\AtEndDocument{%
  \closeoutputstream{colourfile}% Close colour.txt
}

\definecolor{lemon}{rgb}{1.0, 0.97, 0.0}
\definecolor{maize}{rgb}{0.98, 0.93, 0.37}
\definecolor{mustard}{rgb}{1.0, 0.86, 0.35}
\definecolor{ocre}{HTML}{F16723}
\definecolor{Tangerine}{RGB}{253,128,8}

\begin{document}

\textcolor{lemon}{lemon}
\textcolor{maize}{maize}
\textcolor{mustard}{mustard}
\textcolor{ocre}{ocre}
\textcolor{Tangerine}{Tangerine}

\end{document}

The file colour.txt now contains:

\definecolor{lemon}{RGB}{255,247,0}
\definecolor{maize}{RGB}{250,237,94}
\definecolor{mustard}{RGB}{255,219,89}
\definecolor{ocre}{RGB}{241,103,35}
\definecolor{Tangerine}{RGB}{253,128,8}
Related Question