Search code examples
matlabcolorskmlkmz

How can I convert an RGB color to a KML hexadecimal color string?


In MATLAB I have data defined by x,y,z coordinate values and color. Now I want to create a kmz file for Google Earth using the KLM Toolbox. In order to define a Color array I use the 'iconColor' property for which the input "Must be a valid hex color string input, in the style AABBGGRR".

What is a good way to transform my array of RGB colors to hex color strings? What if I want to use different colormaps (jet or winter)?


Solution

  • The built-in colormaps in MATLAB will give you matrices of RGB color triples that are scaled from 0 (lowest intensity) to 1 (highest intensity). To convert a single RGB triple to its KML color style equivalent (with the AABBGGRR format), the steps are:

    • Scale it from 0 to 255.
    • Flip the order to BGR.
    • Add a transparency value to the beginning (0 for fully transparent, 255 for fully opaque).
    • Convert to a uint8 type to ensure you have integers in the range 0 to 255.
    • Convert to hexdecimal strings using dec2hex.
    • Reshape the result into a 1-by-8 array of characters.

    And here is an example:

    >> color = [1 1 0];  % The RGB triple for yellow
    >> hexColor = reshape(dec2hex(uint8([255 255.*flip(color, 2)])).', 1, 8)
    
    hexColor =
    
    FF00FFFF
    

    If you want to convert an entire colormap (i.e. an N-by-3 matrix, one RGB triple per row), you can modify the above code like so:

    >> N = 10;        % Number of colors
    >> map = jet(N);  % 10-by-3 jet colormap
    >> hexMap = reshape(dec2hex(uint8([255.*ones(N, 1) 255.*flip(map, 2)]).').', 8, []).'
    
    hexMap =
    
    FFAA0000
    FFFF0000
    FFFF5500
    FFFFAA00
    FFFFFF00
    FFAAFF55
    FF55FFAA
    FF00FFFF
    FF00AAFF
    FF0055FF