Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.