Skip to content
Advertisement

Display the Color in a box for input RGB values in html/php

The code given below will give the Hex value after submission , but i also require a square box and a corresponding color filled in the box. want to get the red, green and blue value and want to display the color of that RGB value in a square box .

<head>
<style type="text/css">

#redv:focus {
  background-color: PowderBlue;
}
#bluev:focus {
  background-color: PowderBlue;
}

#greenv:focus {
  background-color: PowderBlue;
}

#button1:hover {
  background-color: CadetBlue; 
  font-size: 16px;
  color: white; 
  border: 2px solid #008CBA;
}

#button1 {
  background-color: #008CBA;
  font-size: 16px;
  color: white;
}



input[type="color"] {
    -webkit-appearance: none;
    border: none;
    width: 102px;
    height: 102px;
}



</style>
</head>
<body>  
<form>  
Enter Red Value:  
<input type="number" id="redv" name="red" value="0" max="255"/> (Max:255)<br><br>

Enter Green Value:  
<input type="number" id="greenv" name="green" value="0" max="255"/> (Max:255) <br><br>

Enter Blue Value:  
<input type="number" id="bluev" name="blue" value="0" max="255"/>(Max:255) <br><br>

<input  type="submit" name="submit" value="Generate" id="button1"> 
 
</form>  


</body>  



<?php      
@$red=$_GET['red'];   
@$green=$_GET['green']; 
@$blue=$_GET['blue'];     




function rgb2hex($rgb) {
   $hex = "#";
   $hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
   $hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);
   $hex .= str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT);

   return $hex; // returns the hex value including the number sign (#)
}

$rgb = array( $red, $green, $blue );
$hex = rgb2hex($rgb);
echo $hex;

?>  

The objective is to get something like this, we will get input from user in Red, Green and Blue and will display that color in a square box as shown below.

enter image description here

Advertisement

Answer

Minimized the rgb2hex function and added a div with required style instead of input[type=color]

<?php      

$color = sprintf("#%02x%02x%02x", $_GET['red'], $_GET['green'] , $_GET['blue']);
echo '<div style="width:102px; height:102px; background-color:'.$color.';"></div>';

?>  

or

<style>
  div{
    width: 102px;
    height: 102px;
    border: none;
  }
</style>

<?php      

$color = sprintf("#%02x%02x%02x", $_GET['red'], $_GET['green'] , $_GET['blue']);
echo '<div style="background-color:'.$color.';"></div>';

?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement