shedokan Posted April 3, 2009 Share Posted April 3, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/152449-convert-rgb-to-hex/ Share on other sites More sharing options...
MadTechie Posted April 4, 2009 Share Posted April 4, 2009 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'); Quote Link to comment https://forums.phpfreaks.com/topic/152449-convert-rgb-to-hex/#findComment-800987 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.