c color转html,C#: Convert Drawing.Color to HTML Hex Color Value and Back

I was working on a small project that needed to colorize text from stored values and bitmap gradients which involved getting color values from individual pixels as RGB values or System.Drawing.Color values. The following code demonstrates how to convert back-and-forth between System.Drawing.Color and string values (#XXXXXX or the name). I’ve seen how some people have gone out of their way to do these conversions with their own code implementations, but why recreate what’s already in the .NET Framework?

I must admit though, I didn’t think this was already built-in until I searched MSDN. 1 usingSystem.Drawing;2 usingSystem;3 4 publicpartialclassColorConvert : System.Web.UI.Page5 {6 protectedvoidPage_Load(objectsender, EventArgs e)7 {8 //convert to the HTML color value of a9 //known System.Drawing.Color10 stringhtmlNamedColorValue=11 ColorTranslator.ToHtml(Color.Crimson);12 //output: "Crimson"13 14 //convert to the HTML hex color value from15 //System.Drawing.Color with RGB values (208,0,0)16 stringhtmlHexColorValueTwo=17 ColorTranslator.ToHtml(Color.FromArgb(0,208,0,0));18 //output: "#D00000"19 20 //convert to System.Drawing.Color from HTML hex color value21 Color colorValueFrmHex=22 ColorTranslator.FromHtml("#FFFF33");23 //output: System.Drawing.Color with RGB values (255,25,51)24 25 //convert to System.Drawing.Color from HTML known color26 Color colorValue=27 ColorTranslator.FromHtml("DarkRed");28 //output: Color.DarkRed29

30 stringhtmlHexColorValueThree=31 String.Format("#{0:X2}{1:X2}{2:X2}", colorValue.R,32 colorValue.G,33 colorValue.B);34 //output: "#8B0000"35 }36 }

KickItImageGenerator.ashx?url=http%3a%2f%2fxiirus.net%2farticles%2farticle-c-convert-drawing_color-to-html-hex-color-value-and-back-cc8mp.aspx

Tags:

.NET, ASP.NET, C#, Code, How To, HTML, Programming, Tips

button1-share.gif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值