php实现颜色面板
PHP 实现颜色面板的方法
使用 HTML 和 PHP 生成基础颜色选择器
通过 HTML 的 input 类型为 color 可以直接调用浏览器原生颜色选择器,PHP 用于处理提交后的颜色值。
<form method="post">
<label for="color">选择颜色:</label>
<input type="color" id="color" name="color" value="#ff0000">
<input type="submit" value="提交">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$selectedColor = $_POST['color'];
echo "你选择的颜色是:<span style='color: $selectedColor'>$selectedColor</span>";
}
?>
自定义颜色面板生成
通过 PHP 动态生成颜色块,支持 HEX 或 RGB 格式。

function generateColorPalette($step = 30) {
echo "<div style='display: flex; flex-wrap: wrap; width: 300px;'>";
for ($r = 0; $r <= 255; $r += $step) {
for ($g = 0; $g <= 255; $g += $step) {
for ($b = 0; $b <= 255; $b += $step) {
$hex = sprintf("#%02x%02x%02x", $r, $g, $b);
echo "<div style='width: 20px; height: 20px; background: $hex;' title='$hex'></div>";
}
}
}
echo "</div>";
}
generateColorPalette();
集成第三方库(如 jQuery 插件)
通过 PHP 输出包含第三方颜色选择器的 HTML/Javascript 代码。

echo <<<HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.1/spectrum.min.css">
<input type="text" id="color-picker">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.1/spectrum.min.js"></script>
<script>
$("#color-picker").spectrum({
color: "#f00",
preferredFormat: "hex"
});
</script>
HTML;
使用 GD 库生成颜色渐变图
通过 PHP 的 GD 库动态创建渐变颜色图像。
header("Content-type: image/png");
$width = 256;
$height = 256;
$image = imagecreatetruecolor($width, $height);
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$color = imagecolorallocate($image, $x, $y, 128);
imagesetpixel($image, $x, $y, $color);
}
}
imagepng($image);
imagedestroy($image);
颜色转换工具函数
提供常用颜色格式转换的 PHP 函数。
function hexToRgb($hex) {
$hex = str_replace("#", "", $hex);
if (strlen($hex) == 3) {
$r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
$g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
$b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
} else {
$r = hexdec(substr($hex, 0, 2));
$g = hexdec(substr($hex, 2, 2));
$b = hexdec(substr($hex, 4, 2));
}
return array($r, $g, $b);
}
function rgbToHex($r, $g, $b) {
return "#" . sprintf("%02x%02x%02x", $r, $g, $b);
}






