IT Share you

PHP에서 16 진수 색상을 RGB 값으로 변환

shareyou 2020. 11. 15. 12:02
반응형

PHP에서 16 진수 색상을 RGB 값으로 변환


PHP를 사용하여 16 진수 색상 값을 #ffffff단일 RGB 값으로 변환하는 좋은 방법은 무엇입니까 255 255 255?


PHP hexdec()dechex()기능 확인 : http://php.net/manual/en/function.hexdec.php

예:

$value = hexdec('ff'); // $value = 255

16 진수를 rgb로 변환하려면 다음을 사용할 수 있습니다 sscanf.

<?php
$hex = "#ff9900";
list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
echo "$hex -> $r $g $b";
?>

산출:

#ff9900 -> 255 153 0

알파가 두 번째 매개 변수로 제공되면 알파를 반환하는 함수를 만들었습니다.

함수

function hexToRgb($hex, $alpha = false) {
   $hex      = str_replace('#', '', $hex);
   $length   = strlen($hex);
   $rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
   $rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
   $rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
   if ( $alpha ) {
      $rgb['a'] = $alpha;
   }
   return $rgb;
}

함수 응답의 예

print_r(hexToRgb('#19b698'));
Array (
   [r] => 25
   [g] => 182
   [b] => 152
)

print_r(hexToRgb('19b698'));
Array (
   [r] => 25
   [g] => 182
   [b] => 152
)

print_r(hexToRgb('#19b698', 1));
Array (
   [r] => 25
   [g] => 182
   [b] => 152
   [a] => 1
)

print_r(hexToRgb('#fff'));
Array (
   [r] => 255
   [g] => 255
   [b] => 255
)

rgb (a)를 CSS 형식으로 반환 return $rgb;하려면 함수 줄을return implode(array_keys($rgb)) . '(' . implode(', ', $rgb) . ')';


관심이있는 사람에게 이것은 매우 간단한 방법입니다. 이 예에서는 정확히 6자가 있고 앞에 파운드 기호가 없다고 가정합니다.

list($r, $g, $b) = array_map('hexdec', str_split($colorName, 2));

다음은 4 개의 다른 입력 (abc, aabbcc, #abc, #aabbcc)을 지원하는 예입니다.

list($r, $g, $b) = array_map(function($c){return hexdec(str_pad($c, 2, $c));}, str_split(ltrim($colorName, '#'), strlen($colorName) > 4 ? 2 : 1));

함수 hexdec(hexStr: String)사용하여 16 진 문자열의 10 진수 값을 가져올 수 있습니다 .

예는 아래를 참조하십시오.

$split = str_split("ffffff", 2);
$r = hexdec($split[0]);
$g = hexdec($split[1]);
$b = hexdec($split[2]);
echo "rgb(" . $r . ", " . $g . ", " . $b . ")";

이것은 인쇄됩니다 rgb(255, 255, 255)


해시, 단일 값 또는 쌍 값을 사용하거나 사용하지 않고 16 진수 색상을 처리하는 방법 :

function hex2rgb ( $hex_color ) {
    $values = str_replace( '#', '', $hex_color );
    switch ( strlen( $values ) ) {
        case 3;
            list( $r, $g, $b ) = sscanf( $values, "%1s%1s%1s" );
            return [ hexdec( "$r$r" ), hexdec( "$g$g" ), hexdec( "$b$b" ) ];
        case 6;
            return array_map( 'hexdec', sscanf( $values, "%2s%2s%2s" ) );
        default:
            return false;
    }
}
// returns array(255,68,204)
var_dump( hex2rgb( '#ff44cc' ) );
var_dump( hex2rgb( 'ff44cc' ) );
var_dump( hex2rgb( '#f4c' ) );
var_dump( hex2rgb( 'f4c' ) );
// returns false
var_dump( hex2rgb( '#f4' ) );
var_dump( hex2rgb( 'f489' ) );

아래에서이 간단한 코드를 시도해 볼 수 있습니다.

list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;

그러면 123,222,132가 반환됩니다.


@John의 답변과 @iic의 코멘트 / 아이디어를 일반적인 16 진수 색상 코드와 속기 색상 코드를 모두 처리 할 수있는 함수에 통합했습니다.

간단한 설명 :

scanf를 사용 하여 16 진수 색상의 r, g 및 b 값을 문자열로 읽습니다. @John의 대답과 같은 16 진수 값이 아닙니다. 속기 색상 코드를 사용하는 경우 r, g 및 b 문자열을 십진수로 변환하기 전에 두 배 ( "f"-> "ff"등)해야합니다.

function hex2rgb($hexColor)
{
  $shorthand = (strlen($hexColor) == 4);

  list($r, $g, $b) = $shorthand? sscanf($hexColor, "#%1s%1s%1s") : sscanf($hexColor, "#%2s%2s%2s");

  return [
    "r" => hexdec($shorthand? "$r$r" : $r),
    "g" => hexdec($shorthand? "$g$g" : $g),
    "b" => hexdec($shorthand? "$b$b" : $b)
  ];
}

색상 코드 HEX를 RGB로 변환

$color = '#ffffff';
$hex = str_replace('#','', $color);
if(strlen($hex) == 3):
   $rgbArray['r'] = hexdec(substr($hex,0,1).substr($hex,0,1));
   $rgbArray['g'] = hexdec(substr($hex,1,1).substr($hex,1,1));
   $rgbArray['b'] = hexdec(substr($hex,2,1).substr($hex,2,1));
else:
   $rgbArray['r'] = hexdec(substr($hex,0,2));
   $rgbArray['g'] = hexdec(substr($hex,2,2));
   $rgbArray['b'] = hexdec(substr($hex,4,2));
endif;

print_r($rgbArray);

산출

Array ( [r] => 255 [g] => 255 [b] => 255 )

나는 여기 에서이 참조를 찾았습니다 -PHP를 사용하여 Color Hex를 RGB로, RGB를 Hex로 변환


이것을 시도하면 인수 (r, g, b)를 16 진수 html 색상 문자열로 변환합니다. #RRGGBB 인수는 정수로 변환되고 0..255 범위로 잘립니다.

<?php
function rgb2html($r, $g=-1, $b=-1)
{
    if (is_array($r) && sizeof($r) == 3)
        list($r, $g, $b) = $r;

    $r = intval($r); $g = intval($g);
    $b = intval($b);

    $r = dechex($r<0?0:($r>255?255:$r));
    $g = dechex($g<0?0:($g>255?255:$g));
    $b = dechex($b<0?0:($b>255?255:$b));

    $color = (strlen($r) < 2?'0':'').$r;
    $color .= (strlen($g) < 2?'0':'').$g;
    $color .= (strlen($b) < 2?'0':'').$b;
    return '#'.$color;
}
?>

아 그리고 반대 방향

# 처음에있는 문자는 생략 할 수 있습니다. 함수는 범위 (0..255)에있는 세 개의 정수 배열을 반환하거나 색상 형식을 인식하지 못하면 false를 반환합니다.

<?php
function html2rgb($color)
{
    if ($color[0] == '#')
        $color = substr($color, 1);

    if (strlen($color) == 6)
        list($r, $g, $b) = array($color[0].$color[1],
                                 $color[2].$color[3],
                                 $color[4].$color[5]);
    elseif (strlen($color) == 3)
        list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
    else
        return false;

    $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);

    return array($r, $g, $b);
}
?>

//if u want to convert rgb to hex
$color='254,125,1';
$rgbarr=explode(",", $color);
echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]);

This is the only solution that worked for me. Some of the answers were not consistent enough.

    function hex2rgba($color, $opacity = false) {

        $default = 'rgb(0,0,0)';

        //Return default if no color provided
        if(empty($color))
              return $default;

        //Sanitize $color if "#" is provided
            if ($color[0] == '#' ) {
                $color = substr( $color, 1 );
            }

            //Check if color has 6 or 3 characters and get values
            if (strlen($color) == 6) {
                    $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
            } elseif ( strlen( $color ) == 3 ) {
                    $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
            } else {
                    return $default;
            }

            //Convert hexadec to rgb
            $rgb =  array_map('hexdec', $hex);

            //Check if opacity is set(rgba or rgb)
            if($opacity){
                if(abs($opacity) > 1)
                    $opacity = 1.0;
                $output = 'rgba('.implode(",",$rgb).','.$opacity.')';
            } else {
                $output = 'rgb('.implode(",",$rgb).')';
            }

            //Return rgb(a) color string
            return $output;
    }
    //hex2rgba("#ffaa11",1)

참고URL : https://stackoverflow.com/questions/15202079/convert-hex-color-to-rgb-values-in-php

반응형