Jump to content

Convert RGB to hex?


shedokan

Recommended Posts

I am trying to make an image array so I need to convert RGB values to hex.

here's my code:

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;
}
$im = imagecreatefromgif('image.gif');
$imh=imagesy($im);
$imw=imagesx($im);
$image=array();
$y=0;
do{
	$image[$y]=array();
	$x=0;
	do{
		$rgb = imagecolorat($im, $x, $y);
		$r = ($rgb >> 16) & 0xFF;
		$g = ($rgb >>  & 0xFF;
		$b = $rgb & 0xFF;
		$hex=rgb2html($r,$g,$b);
		$image[$y][$x]=$hex;
	} while(++$x<=$imw-1);
} while(++$y<=$imh-1);

 

it converts correctly some of the colors and some not.

 

thanks.

Link to comment
https://forums.phpfreaks.com/topic/152449-convert-rgb-to-hex/
Share on other sites

If you want it for HTML then HTML can handle Hex

ie

<?php
    function rgbhex($red, $green, $blue)
    {
        return sprintf('#%02X%02X%02X', $red, $green, $blue);
    }

    echo rgbhex(15, 15, 15); // prints #0F0F0F
?>

if you want to convert decimal to hexadecimal use dechex(10); or hexadecimal to decimal hexdec('a');

Link to comment
https://forums.phpfreaks.com/topic/152449-convert-rgb-to-hex/#findComment-800987
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.