将css颜色转换为16位rgb

时间:2014-02-09 19:22:25

标签: applescript hex

我正在尝试将129a8f之类的css十六进制颜色转换为适合choose color default color xxx的格式(在本例中为{4626, 39578, 36751})。我有红宝石代码可以解决问题

if m = input.match('([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})') then
  clr = "{#{m[1].hex*257}, #{m[2].hex*257}, #{m[3].hex*257}}"

现在我在AppleScript中需要相同的东西(我不知道;)。有什么指针吗?

1 个答案:

答案 0 :(得分:2)

您可以在AppleScript脚本中使用ruby

set x to text returned of (display dialog "Type a css hex color." default answer "129a8f")
set xx to do shell script "/usr/bin/env ruby -e  'x=\"" & x & "\"; if m= x.match(\"([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})\") then puts \"{#{m[1].hex*257}, #{m[2].hex*257}, #{m[3].hex*257}}\"; end' "
if xx is "" then
    display alert x & " is not a valid css hex color" buttons {"OK"} cancel button "OK"
else
    set xxx to run script xx -- convert ruby string to AppleScript list
    set newColor to choose color default color xxx
end if

-

或没有ruby的AppleScript脚本

property hexChrs : "0123456789abcdef"

set x to text returned of (display dialog "Type a css hex color." default answer "129a8f")
set xxx to my cssHexColor_To_RGBColor(x)
set newColor to choose color default color xxx

on cssHexColor_To_RGBColor(h) -- convert 
    if (count h) < 6 then my badColor(h)
    set astid to text item delimiters
    set rgbColor to {}
    try
        repeat with i from 1 to 6 by 2
            set end of rgbColor to ((my getHexVal(text i of h)) * 16 + (my getHexVal(text (i + 1) of h))) * 257
        end repeat
    end try
    set text item delimiters to astid
    if (count rgbColor) < 3 then my badColor(h)
    return rgbColor
end cssHexColor_To_RGBColor

on getHexVal(c)
    if c is not in hexChrs then error
    set text item delimiters to c
    return (count text item 1 of hexChrs)
end getHexVal

on badColor(n)
    display alert n & " is not a valid css hex color" buttons {"OK"} cancel button "OK"
end badColor