好了,沒有什麼語言內置的。將十六進制轉換爲十進制就像CLng("&H" & hexValue)
一樣簡單,但是從快速查看PHP手冊中看到,hexdec()
方法忽略任何無效字符,而VBScript CLng()
只會崩潰。
因此,這裏是一個工作的功能,據我可以告訴做同樣的事情:
Function GetContrast50(hexColor)
Const strValidChars = "1234567890abcdef"
Dim maxValue, decValue, sanitizedColor
Dim x, curChar
sanitizedColor = ""
For x=1 To Len(hexColor)
curChar = LCase(Mid(hexColor, x, 1))
If InStr(strValidChars, curChar)>0 Then
sanitizedColor = sanitizedColor & curChar
End If
Next
If Len(sanitizedColor)=0 Then
GetContrast50 = "invalid color string"
Exit Function
End If
maxValue = CLng("&H" & "ffffff")
decValue = CLng("&H" & sanitizedColor)
If decValue > (maxValue/2) Then
GetContrast50 = "black"
Else
GetContrast50 = "white"
End If
End Function
這是很容易擴展的驗證檢查給定的字符串是在有效範圍內。
感謝您的代碼,它似乎做我在找什麼。 – jbwharris 2013-02-27 16:11:43
我注意到它正在進行的計算有一個問題。使用像#FFE6E6(淡粉紅色)這樣的值,我最終返回白色,這太輕而無法打開白色文本。我不確定在計算中是否存在問題。 – jbwharris 2013-02-27 19:34:34
@jamEs哦,我的,對不起!由於在我的代碼中「#FFE6E6」中的n00bish錯誤實際上被視爲「66」,因爲大寫字母被認爲是非法字符。現在修復它,看我的編輯。 – 2013-02-27 20:57:04