Page 1 of 1

BASIC Long color to HTML hex color with alpha

Posted: Sat Jan 11, 2020 4:21 pm
by Evgeniy

Code: Select all

' Convert Long color value to HTML HEX color for example "#0ffa56"
' If used in HTML tag for example <FONT COLOR> tag use aditional ""
' If used in CSS STYLE for example background-color: not use "" 
Function LongToHTML_Hex(ColorValue as Long) As String
	LongToHTML_Hex="#"+Right("0"+Hex(red(ColorValue)),2)+Right("0"+Hex(green(ColorValue)),2)+Right("0"+Hex(blue(ColorValue)),2)
End Function

' With alpha channel support #RRGGBBAA
' For example #000000FF = black color with 100% transparency
Function LongToHTML_HexAlpha(ColorValue as Long) As String
	LongToHTML_HexAlpha="#"+Right("0"+Hex(red(ColorValue)),2)+Right("0"+Hex(green(ColorValue)),2)+Right("0"+Hex(blue(ColorValue)),2)+_
	Right("0"+Hex(red(ColorValue/256)),2)
End Function
How to use:

1) Simple message box

Code: Select all

msgbox "rgb(215,125,25)="+LongToHTML_Hex(rgb(215,125,25))+chr(10)+chr(10)+" HEX(DEADBEEF)="+LongToHTML_HexAlpha(-559038737)
2) HTML tag make

Code: Select all

...
color=LongToHTML_Hex(TextPortion.CharColor)
text=text+"<FONT COLOR="""+color+""">"+TextPortion.String+"</FONT>"
...

Re: BASIC Long color to HTML hex color with alpha

Posted: Sat Jan 11, 2020 9:52 pm
by JeJe
LongToHTML_Hex(rgb(255,125,255)) gives #FF07FF when it should be #FF7DFF

VB6 code can often be adapted to OOBasic with no to few changes

https://codereview.stackexchange.com/qu ... ing-in-vb6

Re: BASIC Long color to HTML hex color with alpha

Posted: Sat Jan 11, 2020 10:05 pm
by Evgeniy

Code: Select all

Sub Test
	Dim c As Long
	c=rgb(125,125,125)
	msgbox Format(Hex(blue(c)),"00")
End Sub
Yes thats true :( Format function is bugly?
Thanks for bug catch.
Right("0"+Hex(val), 2) interst basic trick!
Functions are Fixed.

Re: BASIC Long color to HTML hex color with alpha

Posted: Sun Jan 12, 2020 1:09 am
by Villeroy
What's wrong with ="#"&DEC2HEX(A1;6) :?:

Re: BASIC Long color to HTML hex color with alpha

Posted: Sun Jan 12, 2020 11:42 am
by JeJe
result = "#000000": mid(result,8 - len(hex(no)))= hex(no)

Re: BASIC Long color to HTML hex color with alpha

Posted: Wed Oct 21, 2020 8:13 am
by rickberon
There is a simple Math behind it. RGB color code contains three numbers, each ranging from 0 to 255. Just convert these number into hexadecimal and put in sequence of #RGB. For Example, RGB(0,0,0) will be #000 and RGB(255, 255, 255) will be #FFFFFF.

How to convert from decimal to hex

Divide the number by 16.
Get the integer quotient for the next iteration.
Get the remainder for the hex digit.
Repeat the steps until the quotient is equal to 0.