PHP에서 16진수 색상을 RGB 값으로 변환
다음과 같은 16진수 색상 값을 변환하는 좋은 방법은 무엇입니까?#ffffff
단일 RGB 값으로 변환합니다.255 255 255
PHP를 사용하시겠습니까?
16진수를 rbg로 변환하려면 sscanf를 사용할 수 있습니다.
<?php
$hex = "#ff9900";
list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
echo "$hex -> $r $g $b";
?>
출력:
#ff9900 -> 255 153 0
PHP 체크hexdec()
그리고.dechex()
기능: http://php.net/manual/en/function.hexdec.php
예:
$value = hexdec('ff'); // $value = 255
아래 코드와 같은 두 번째 파라미터로 알파가 제공되면 알파도 반환하는 함수를 만들었습니다.
함수
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
)
CSS 형식으로 rbg(a)를 반환하고 싶은 경우는, Rbg(a)를 교환해 주세요.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)
아래의 간단한 코드를 사용해 보십시오.
list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;
123,222,132가 반환됩니다.
해시, 단일 값 또는 페어 값의 유무에 관계없이 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' ) );
시작 여부에 관계없이 입력값을 지원하는 간단한 함수를 작성했습니다.#
또한 3자 또는 6자의 16진수 코드를 입력할 수도 있습니다.
function hex2rgb( $color ) {
if ($color[0] == '#') {
$color = substr($color, 1);
}
list($r, $g, $b) = array_map("hexdec", str_split($color, (strlen( $color ) / 3)));
return array( 'red' => $r, 'green' => $g, 'blue' => $b );
}
다음으로 액세스 할 수 있는 관련 어레이를 반환합니다.$color['red']
,$color['green']
,$color['blue']
;
CSS Stricks도 참조해 주세요.
@John의 답변과 @iic의 코멘트/아이디어를 통상의 16진수 컬러 코드와 속기 컬러 코드의 양쪽 모두를 처리할 수 있는 기능으로 정리했습니다.
간단한 설명:
scanf를 사용하여 16진수 색상의 r, g, b 값을 문자열로 읽습니다.@John의 답변처럼 16진수 값이 아닙니다.속기 컬러 코드를 사용하는 경우, r, g 및 b 문자열은 소수점으로 변환하기 전에 2배("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를 사용하여 색상의 16진수를 RGB로 변환하고 RGB를 16진수로 변환합니다.
@jhon's answer에서 차용 - 불투명도 옵션과 함께 문자열 형식으로 rbg를 반환합니다.
function convert_hex_to_rgba($hex, $opacity = 1){
list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
return sprintf('rgba(%s, %s, %s, %s)', $r, $g, $b, $opacity);
}
convert_hex_to_rgba($bg_color, 0.9) // rgba(2,2,2,0.9)
이렇게 하면 인수(r, g, b)를 16진수 html-color 문자열 #RRGBB 인수가 정수로 변환되고 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]);
function RGB($hex = '')
{
$hex = str_replace('#', '', $hex);
if(strlen($hex) > 3) $color = str_split($hex, 2);
else $color = str_split($hex);
return [hexdec($color[0]), hexdec($color[1]), hexdec($color[2])];
}
Enjoy
public static function hexColorToRgba($hex, float $a){
if($a < 0.0 || $a > 1.0){
$a = 1.0;
}
for ($i = 1; $i <= 5; $i = $i+2){
$rgb[] = hexdec(substr($hex,$i,2));
}
return"rgba({$rgb[0]},{$rgb[1]},{$rgb[2]},$a)";
}
솔루션: (단축 표기 지원)
$color = "#0ab";
$colort = trim( $color );
if( $colort and is_string( $color ) and preg_match( "~^#?([abcdef0-9]{3}|[abcdef0-9]{6})$~ui", $colort ))
{
if( preg_match( "~^#?[abcdef0-9]{3}$~ui", $colort ))
{
$hex = trim( $colort, "#" );
list( $hexR, $hexG, $hexB ) = str_split( $hex );
$hexR .= $hexR;
$hexG .= $hexG;
$hexB .= $hexB;
}
else
{
$hex = trim( $colort, "#" );
list( $hexR, $hexG, $hexB ) = str_split( $hex, 2 );
}
$colorR = hexdec( $hexR );
$colorG = hexdec( $hexG );
$colorB = hexdec( $hexB );
}
// Test
echo $colorR ."/" .$colorG ."/" .$colorB;
// → 0/170/187
16진수를 RGB로 하려면 , 다음의 순서에 따릅니다.
class RGB
{
private $color; //#ff0000
private $red;
private $green;
private $blue;
public function __construct($colorCode = '')
{
$this->color = ltrim($colorCode, '#');
$this->parseColor();
}
public function readRGBColor()
{
echo "Red = {$this->red}\nGreen = {$this->green}\nBlue = {$this->blue}";
}
private function parseColor()
{
if ($this->color) {
list($this->red, $this->green, $this->blue) = sscanf($this->color, '%02x%02x%02x');
} else {
list($this->red, $this->green, $this->blue) = array(0, 0, 0);
}
}
}
$myColor = new RGB("#ffffff");
$myColor->readRGBColor();
높은 응답률에 근거합니다.-> https://stackoverflow.com/a/15202130/3884001
function hex2rgba( $color, $opacity ) {
list($r, $g, $b) = sscanf($color, "#%02x%02x%02x");
$output = "rgba($r, $g, $b, $opacity)";
return $output;
}
사용할 수 있는 것보다 더 많은
<?php
$color = '#ffffff';
hex2rgba($color, 0.5);
?>
언급URL : https://stackoverflow.com/questions/15202079/convert-hex-color-to-rgb-values-in-php
'programing' 카테고리의 다른 글
chars [ ]와 char *의 차이점은 무엇입니까? (0) | 2022.09.11 |
---|---|
Laravel의 웅변적인 "IN" 쿼리를 만드는 방법 (0) | 2022.09.11 |
MySQL 쿼리를 CSV로 변환하기 위한 PHP 코드 (0) | 2022.09.08 |
Android ListView헤더 (0) | 2022.09.08 |
목록의 평균 찾기 (0) | 2022.09.08 |