karaimadai
karaimadai

Reputation: 121

Display the color in a box for input RGB values in HTML/PHP

The code given below will display the hexadecimal equivalent of the RGB input. However, I also want to display a square box filled with the color corresponding to the input color like what is shown below:

Desired output example

Code

<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;

?>  

Upvotes: 2

Views: 1103

Answers (1)

Shashank Gb
Shashank Gb

Reputation: 1012

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>';

?>

Upvotes: 2

Related Questions