在 ASP Classic 中将十六进制转换为 RGB

问题描述 投票:0回答:3

您能否告诉我如何在 ASP Classic/VBScript 中将十六进制转换为 RGB。我尝试在互联网上搜索并尝试了许多建议的解决方案,但没有一个指向我想要实现的目标。

我尝试了以下功能,但没有一个起作用: 将十六进制颜色字符串转换为 RGB 颜色

转换为RBB后,我希望根据背景颜色设置文本颜色。所以基本上我的背景颜色代码是十六进制的。

vbscript asp-classic hex rgb
3个回答
1
投票

首先,使用“&h”表示将十六进制代码转换为十进制并解析结果。之后,只需执行基本的按位运算符即可从数字中提取 RGB 值。

Dim hexval : hexval = "fdfeff"

Dim rgbval : rgbval = CLng("&h" & hexval)
Dim r : r = (rgbval And &hff0000&) / 65536
Dim g : g = (rgbval And &h00ff00&) / 256
Dim b : b = (rgbval And &h0000ff&)

wscript.echo Join(Array(hexval, rgbval, r, g, b), vbcrlf)

这会产生以下输出:

fefeff
16645887
253
254
255

0
投票

这是我使用的功能:

Function HexToRGB(HexColor)
    'PURPOSE: Convert Hex Code To RGB Code In Cells

    'Remove # (if applicable)
        Dim RGBColor : RGBColor = Replace(HexColor, "#", "")
    
    'Ensure 6 Characters
        RGBColor = Right("000000" & RGBColor, 6)
    

    'Extract RGB Codes
        RGBColor = CLng("&h" & RGBColor)
        
        Dim r : r = (RGBColor And &hff0000&) / 65536
        Dim g : g = (RGBColor And &h00ff00&) / 256
        Dim b : b = (RGBColor And &h0000ff&)
    
    'Format rrrgggbbb
        'RGBColor = r & g & b
    'or rrr,ggg,bbb
        RGBColor = r & "," & g & "," & b

    'Return the value
        HexToRGB = RGBColor
End Function

希望它对某人有帮助。

您可以根据需要更改底部的返回值。


-1
投票

这有点长,我确信基数 16 函数可能会更有效,但它确实有效。

' Convert Hex to RGB 
Function ConvertHexToRBG(theHexColor)
  Color = Replace(theHexColor, "#", "") 
  Red = (Mid(Color, 1, 2)) 
  Green = (Mid(Color, 3, 2))
  Blue = (Mid(Color, 5, 2))

  ConvertHexToRBG =  "RGB("&ConvertHexToInt(red)&","&ConvertHexToInt(green)&","&ConvertHexToInt(blue)&",1)"
End Function

Function ConvertHexToInt(theStr)
  If theStr <> "" Then 
  SELECT Case Left(theStr,1)
    Case "F"
        T = 15
    Case "E"
        T = 14
    Case "D"
        T = 13
    Case "C"
        T = 12
    Case "B"
        T = 11
    Case "A"
        T = 10
    Case "9"
        T = 9
    Case "8"
        T = 8
    Case "7"
        T = 7
    Case "6"
        T = 6
    Case "5"
        T = 5
    Case "4"
        T = 4
    Case "3"
        T = 3
    Case "2"
        T = 2
    Case "1" 
        T = 1
    CASE "0"
        T = 0
    Case Else
        T = Left(theStr,1)
  End SELECT
  SELECT Case Right(theStr,1)
    Case "F"
        D = 15
    Case "E"
        D = 14
    Case "D"
        D = 13
    Case "C"
        D = 12
    Case "B"
        D = 11
    Case "A"
        D = 10
    Case "9"
        D = 9
    Case "8"
        D = 8
    Case "7"
        D = 7
    Case "6"
        D = 6
    Case "5"
        D = 5
    Case "4"
        D = 4
    Case "3"
        D = 3
    Case "2"
        D = 2
    Case "1" 
        D = 1
    CASE "0"
        D = 0
    Case Else
        D = Right(theStr,1)
  End SELECT
  ConvertHexToInt = CInt(T*16)+CInt(D)
Else
  ConvertHexToInt =  theStr
End If 
© www.soinside.com 2019 - 2024. All rights reserved.