如何通过 php 简单轻松地改变单一 RGB 颜色的亮度?
关于 RGB 颜色以及寻找最简单、最小的 php 转换代码来操作给定 RGB 色调的明度/暗度的问题。
想象一个变量 $colorA
包含有效的六字符 RGB 颜色,例如 F7A100
,我们希望将其变亮和/或变暗:
$color = B1B100; // original RGB color manually set.
然后,在任何页面让颜色动态变暗/变亮:
$colorX = someFunction($color, +10); // original color 10 steps lighter
$colorY = someFunction($color, -25); // original color 25 steps darker
你解决这个问题的方法是什么?保持 RGB 不变还是先将其更改为 HSL?欢迎提示和建议。也欢迎您的示例/代码。
这实际上集中于 TINIES / SIMPLES / SHORTEST 可能的代码,以使相同的色调更暗/更亮。
我故意不建议我的代码,因为我想在这里保持可能性。
A quesion about RGB color and finding the simplest, tiniest, php conversion code for manipulating the lightness/darkness of a given RGB hue.
Imagine a variable $colorA
containning a valid six char RGB color, like F7A100
which we want to make a bit lighter and/or darker:
$color = B1B100; // original RGB color manually set.
Then, at any page have that color bit darker/lighter on the fly:
$colorX = someFunction($color, +10); // original color 10 steps lighter
$colorY = someFunction($color, -25); // original color 25 steps darker
What would be YOUR way of solving this? Keep the RGB as is or first change it to HSL? Hints and suggestions are welcome. Your sample/code is welcome too.
This really focuses to the TINIES / SIMPLES / SHORTEST possible code to just make the same hue bit darker/lighter.
I deliberately do not suggest my code, as I want to keep possibilities open in here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的解决方案是向颜色表示的每个部分添加一些常数(例如 1):
[R, G, B]
。这是因为所有[R, G, B]
的最大值代表白色,而最小值代表黑色。在伪代码中(假设 255 是最大,抱歉,我不懂 PHP):你必须记住,这种转换太简单了,正确的实现是转换为 HSL/HSB,增加 H 并转换回到RGB。
The absolutely simplest solution is to add some constant (like 1) to each part of the color representation:
[R, G, B]
. This is due to the fact that max values of all[R, G, B]
represent white, while min values - black. In pseudo-code (assuming 255 is max, sorry, I don't know PHP):You must keep in mind though that this transformation is way too simplistic and the proper implementation would be to convert to HSL/HSB, increase H and transform back to RGB.
对于亮度的轻微改变,您可以将十六进制值转换为十进制,对其进行操作并转换回十六进制,如下所示:
请注意,此代码不处理一种颜色的溢出 - 如果一种颜色值变得小于 0 或大于 255,您将获取无效的颜色值。这应该很容易添加。
对于亮度的剧烈变化,请转换为 HSL 并操纵亮度。
使用 Drupal 代码中的函数,可以这样完成:
For slight alteration of brightness you can convert the hexadecimal values to decimal, manipulate them and convert back to hexadecimal like this:
Beware that this code does not handle overflow for one color - if one color value becomes less than 0 or more than 255 you will get an invalid color value. This should be easy enough to add.
For drastic changes in brightness, convert to HSL and manipulate the lightness.
Using the functions from the Drupal code, this can be done like this: