计算PHP中两种颜色之间的平均颜色,使用索引号作为参考值 [英] Calculating the average color between two colors in PHP, using an index number as reference value

查看:266
本文介绍了计算PHP中两种颜色之间的平均颜色,使用索引号作为参考值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,我试图计算不同十六进制颜色之间的平均颜色(十六进制)。但是,我还需要能够提供0.0和1.0之间的索引号。

In PHP, I am trying to calculate the average color (in hex) between to different hex colors. However, I also need to be able to supply an index number between 0.0 and 1.0.

例如:

我有

$color1 = "#ffffff" 
$color2 = "#0066CC"

如果我写一个函数来获取平均颜色,我将提供0.0作为索引号,以返回 #ffffff 。如果我提供1.0作为索引号,该函数将需要返回#0066CC 。但是,如果我提供0.2,该函数将需要返回两种颜色之间的平均颜色,但仍然更接近 $ color1 $ color2 。如果我将提供索引号0.5,我会得到两种颜色的确切的平均颜色。

If I would write a function to get the average color and I would supply 0.0 as the index number, the function would need to return "#ffffff". If I would supply 1.0 as the index number, the function would need to return "#0066CC". However if I would supply 0.2, the function would need to return an average color between the two colors, but still closer to $color1 than to $color2. If I would supply index number 0.5, I would get the exact average color of both colors.

我已经试图完成这几天了,但我不能似乎想出来了!

I have been trying to accomplish this for several days now but I can't seem to figure it out! Any help would therefor be greatly appreciated!

推荐答案

让我们假设每种颜色都有一个值为讨论的目的。然后,你想要的就够简单了:

Let's assume that each color has a "value" for the purposes of this discussion. Then, what you want would be simple enough to do:

$index = 0.2;
$val1 = get_value_of_color($color1);
$val2 = get_value_of_color($color2);
$newval = $val1 * $index + $val2 * (1 - $index);
$newcolor = get_color_from_value($newval);

所以,硬的部分是找出每个颜色的值。

So, the hard part is figuring out what the "value" of each color is.

您可以使用简单的RGB值,其中每个颜色的值是一组三个整数:

You could go with simple RGB values, where the "value" of each color is a set of three integers:

function get_value_of_color($color) {
    // assume $color is in the form #xxxxxx
    return array(
        hexdec(substr($color, 1, 2)),
        hexdec(substr($color, 3, 2)),
        hexdec(substr($color, 5, 2)),
    );
}

function get_color_from_value($value) {
    return sprintf('#%02x%02x%02x', $value[0], $value[1], $value[2]);
}

需要在每个数组元素上分别进行乘法和加法。我认为在这一点上,应该很容易做一个简单易用的功能来自己混合颜色。

The multiplications and addition would need to be done on each array element separately here. I think at this point it should be easy to make a simple-to-use function to mix colors yourself.

如果这不是你需要的,那么你可以去具有HSL值或一些更适合您的应用程序的其他指标。这个想法将保持不变。

If this is not what you need, then you can go with HSL values or some other metric that better suits your application. The idea would remain the same.

这篇关于计算PHP中两种颜色之间的平均颜色,使用索引号作为参考值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆