[英]How to convert RGB string into Hex string
我需要將 RGB 轉換為十六進制代碼。
我有字符串格式的顏色"RGB(r, g, b)"
,我需要將其轉換為"#000000"
。
例如,對於"rgb(208,2,27)"
,output 應該是"#D0021B"
像這樣使用 string.Format ,其中 r, gb 是您的值,
string.Format("{0:X2}{1:X2}{2:X2}", r, g, b)
嘗試這個:
string test = "RGB(208,2,27)";
// Remove "RGB(" and ")", then split remainder by "," and parse into an int array.
var rgb = test.Substring(4, test.Length - 5).Split(',').Select(int.Parse).ToArray();
// Create Color object from RGB components.
Color colour = Color.FromArgb(rgb[0], rgb[1], rgb[2]);
// Convert colour into HTML colour string.
string result = ColorTranslator.ToHtml(colour);
Console.WriteLine(result); // Outputs "#D0021B"
要編譯此代碼,您需要引用“System.Drawing”並添加“使用 System.Drawing;” 和“使用 System.Linq;”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.