/// <summary> /// Replace all rgb(#,#,#) and rgba(#,#,#,1) strings with their hex value, /// Replace all hsl(#,#,#) and hsla(#,#,#,1) strings with their hex value. /// </summary> private static void ConvertColors( ref string source ) { var colors = new ColorConversions(); char[] parens = { '(', ')' }; string[] nums; source = Regex.Replace( source, "rgba?\\(\\d{1,3},\\d{1,3},\\d{1,3}(,1)?\\)", m => { nums = m.Value.Split( parens )[ 1 ].Split( ',' ); try { byte[] rgb = { Byte.Parse( nums[ 0 ] ), Byte.Parse( nums[ 1 ] ), Byte.Parse( nums[ 2 ] ) }; return m.Value.Replace( m.Value, colors.ConvertRgbToHex( rgb ) ); } catch( Exception e ) { if( e is ArgumentNullException || e is FormatException || e is OverflowException ) { MessageBox.Show( "Failed to parse " + m.Value, "Parse Error" ); } else { throw; } } return m.Value; } ); // Have to '{0,1}' the '%' since they may have been removed in a previous step source = Regex.Replace( source, "hsla?\\(\\d{1,3},\\d{1,3}%?,\\d{1,3}%?(,1)?\\)", m => { nums = m.Value.Replace( "%", string.Empty ).Split( parens )[ 1 ].Split( ',' ); double h, s, l; try { h = Double.Parse( nums[ 0 ] ) / 360; s = Double.Parse( nums[ 1 ] ) / 100; l = Double.Parse( nums[ 2 ] ) / 100; return m.Value.Replace( m.Value, colors.ConvertHslToHex( h, s, l ) ); } catch( Exception ex ) { if( ex is ArgumentNullException || ex is FormatException || ex is OverflowException ) { MessageBox.Show( "Failed to parse " + m.Value, "Parse Error" ); } else { throw; } } return m.Value; } ); }