hex to hsl php

convert Hsl to rgb and hex

I need a color converter to convert from hsl to rgb and hex value. I am going to do similar like this. I am using jquery and jquery ui range slider for this. Here is my code:

I want the solution like this:

Is there any way to do this?
if no way, what can I do?

6 Answers 6

New approach (inspired by @Kamil-Kiełczewski solution)
Takes degree, percentage, percentage and returns css hex color:

Example:

Original version: (still OK, just longer)

Takes degree, percentage, percentage and returns css hex color:

Example:

hex to hsl php. Смотреть фото hex to hsl php. Смотреть картинку hex to hsl php. Картинка про hex to hsl php. Фото hex to hsl php

HSL to RGB:

Shortest

hex to hsl php. Смотреть фото hex to hsl php. Смотреть картинку hex to hsl php. Картинка про hex to hsl php. Фото hex to hsl php

Another way to solve this problem is to leverage the window.getComputedStyle capability of modern browsers:

Set a color-valued property of that element using the representation of your choice, e.g. e.style.color = ‘hsla(100, 50%, 75%, 0.8)’; (or even named colors like ‘rebeccapurple’ )

I’ve made a small library that can easily convert colors.

This is my HSL to RGB method, which uses a few other utility methods from the library:

If you don’t want to use npm, the lib can also be found on GitHub.

I recently had cause to solve this problem and came up with a canvas-based solution. I’m logging it here for posterity only.

In my case I also needed to account for the cumulative effects on the conversion given a range of background colors and a semi-transparent alpha channel.

Anyway, I achieved what I needed to, and perhaps this will be of some use to someone, sometime.

Источник

Mapping hex/hsl values to a color range

Given a hex/rgb/hsl value, how could I fit that value into a custom range of say 11 basic colors like red, blue etc

The best I could do is match by eye the range of hues in hsl but saturation and lightness can change the perceived color.

Im looking for an algorithm to fit said values in a color range.

1 Answer 1

If you’re only talking 11 basic colors (say red, orange, yellow, green, cyan, blue, purple, magenta, black, white, gray), I would say you’re already there. Hue matching is all you’ll need to match the colors themselves, as long as they’re within a reasonable range of S and L.

To my eye, any L greater than 95ish is close enough to white, and any L less than 5ish is close enough to black.

Then if your S is less than say 10, your options are black, gray, and white, depending on the L, and you can even use the same rules. Black = 95, otherwise gray.

To match hue then, using my example color list, you can’t really use a uniform range, since the differences between colors on the red end of the spectrum are much smaller than those on the cyan end. You could either define them by hand or you might be able to get pretty good results using a logistic function.

TL:DR; Math stuff, probably overkill.

I would just eyeball the hue as making a formula for this is unnecessary and complex.

With that said, here’s my attempt at a logistic function that matches perception of common colors.

hex to hsl php. Смотреть фото hex to hsl php. Смотреть картинку hex to hsl php. Картинка про hex to hsl php. Фото hex to hsl php

You can tweak the k value to whatever you want. I think 1.1 gave a reasonable spread (although I only tried a couple values). The 8 gives you the number of values you would want to get out of this function. So since we have 8 different colors we’re trying to match (in addition to black, white, and gray), I used 8.

The 3 shifts the domain to the right by 3 units. I used 3 because it is half of the domain we are going to use for this function (3 units on either side of the midpoint).

To clarify, this is the final function:

hex to hsl php. Смотреть фото hex to hsl php. Смотреть картинку hex to hsl php. Картинка про hex to hsl php. Фото hex to hsl php

Since it starts at cyan, you have to tweak your hue input value so that 0 is equivalent to the very edge of what you consider cyan and not green. Let’s go with 150 for this example. This means that cyan has a width of 60 degrees, which is where I got the 1.1 K value from, since that lines up pretty well.

We can then plug that into our f(x) and get a number between 0 and 8 which we can use to get our suspected color. If we make an array of the colors, we can just floor the value and use it as an index, since our domain of 0-6 will give us a range of about 0.36-7.7, so it won’t ever get above 8 or below 0.

[cyan, blue, purple, magenta, red, orange, yellow, green]

Is this overkill? Probably.

Is it more interesting? Definitely.

Finally, the code

This all depends on your use case and which colors you are trying to use, so ymmv, but if you want a formula and not a hard coded list, a logistic function like this will likely be your best bet at mirroring perceived color from hues.

Even more overkill. Because why not?

If you wanted more options with S and L, for example to have extra shades of color, you could use the same style of logistic function or even just a linear function.

Lightness will obey the very same function. Medium gray would be the largest slice of the pie, so you would set x=0 to be the lower bound of medium gray.

Saturation is more of a logarithmic function. The first 25% or so has several recognizable shades, while the upper 75% has far less. Something like

hex to hsl php. Смотреть фото hex to hsl php. Смотреть картинку hex to hsl php. Картинка про hex to hsl php. Фото hex to hsl php

Where N is the number of shades to recognize. The domain of this function is 0-100 and the range is 0-N. You can tweak k to your liking to change the width of the steps, but even leaving k as 1 should give adequate results.

Источник

Конвертер цветов

С помощью универсального конвертер цветов вы можете легко перевести цвет из одной цветовой модели в ряд других.

В первую очередь, калькулятор служит для удобной работы с современными форматами CSS3-цветов. Поддерживается конвертация из HEX в RGB/RGBA и HSL/HSLA, RGB в CMYK, XYZ, LAB, и обратно.

А также специальный функционал для замещения альфа-канала при переводе цвета из RGBA в RGB (и HSLA в HSL).

Справка по цветовым моделям

Далее приводится краткое описание цветовых систем с которыми работает конвертер, разъяснение по форматам, а также примеры использования полученных цветов в CSS/HTML.

HEX / HTML

Цвет в формате HEX — это ни что иное, как шестнадцатеричное представление RGB.

Цвета представляются в виде трёх групп шестнадцатеричных цифр, где каждая группа отвечает за свой цвет: #112233, где 11 — красный, 22 — зелёный, 33 — синий. Все значения должны быть между 00 и FF.

Во многих приложениях допускается сокращённая форма записи шестнадцатеричных цветов. Если каждая из трёх групп содержит одинаковые символы, например #112233, то их можно записать как #123.

Цветовое пространство RGB (Red, Green, Blue) состоит из всех возможных цветов, которые могут быть получены путём смешивания красного, зелёного, и синего. Эта модель популярна в фотографии, телевидении, и компьютерной графике.

Значения RGB задаются целым числом от 0 до 255. Например, rgb(0,0,255) отображается как синий, так как синий параметр установлен в его самое высокое значение (255), а остальные установлены в 0.

Некоторые приложения (в частности веб-браузеры) поддерживают процентную запись значений RGB (от 0% до 100%).

Цветовые значения RGB поддерживаются во всех основных браузерах.

С недавних пор современные браузеры научились работать с цветовой моделью RGBA — расширением RGB с поддержкой альфа-канала, который определяет непрозрачность объекта.

Значение цвета RGBA задается в виде: rgba(red, green, blue, alpha). Параметр alpha — это число в диапазоне от 0.0 (полностью прозрачный) до 1.0 (полностью непрозрачный).

RGBA поддерживается в IE9+, Firefox 3+, Chrome, Safari, и в Opera 10+.

Цветовая модель HSL является представлением модели RGB в цилиндрической системе координат. HSL представляет цвета более интуитивным и понятным для восприятия образом, чем типичное RGB. Модель часто используется в графических приложениях, в палитрах цветов, и для анализа изображений.

HSL расшифровывается как Hue (цвет/оттенок), Saturation (насыщенность), Lightness/Luminance (светлота/светлость/светимость, не путать с яркостью).

Hue задаёт положение цвета на цветовом круге (от 0 до 360). Saturation является процентным значением насыщенности (от 0% до 100%). Lightness является процентным значением светлости (от 0% до 100%).

HSL поддерживается в IE9+, Firefox, Chrome, Safari, и в Opera 10+.

По аналогии с RGB/RGBA, для HSL имеется режим HSLA с поддержкой альфа-канала для указания непрозрачности объекта.

Значение цвета HSLA задается в виде: hsla(hue, saturation, lightness, alpha). Параметр alpha — это число в диапазоне от 0.0 (полностью прозрачный) до 1.0 (полностью непрозрачный).

Цветовая модель CMYK часто ассоциируется с цветной печатью, с полиграфией. CMYK (в отличие от RGB) является субтрактивной моделью, это означает что более высокие значения связаны с более тёмными цветами.

Цвета определяются соотношением голубого (Cyan), пурпурного (Magenta), жёлтого (Yellow), с добавлением чёрного (Key/blacK).

Каждое из чисел, определяющее цвет в CMYK, представляет собой процент краски данного цвета, составляющей цветовую комбинацию, а точнее, размер точки растра, выводимой на фотонаборном аппарате на плёнке данного цвета (или прямо на печатной форме в случае с CTP).

Например, для получения цвета «PANTONE 7526» следует смешать 9 частей голубой краски, 83 частей пурпурной краски, 100 — жёлтой краски, и 46 — чёрной. Это можно обозначить следующим образом: (9,83,100,46). Иногда пользуются такими обозначениями: C9M83Y100K46, или (9%, 83%, 100%, 46%), или (0,09/0,83/1,0/0,46).

HSB / HSV

HSB (также известна как HSV) похожа на HSL, но это две разные цветовые модели. Они обе основаны на цилиндрической геометрии, но HSB/HSV основана на модели «hexcone», в то время как HSL основана на модели «bi-hexcone». Художники часто предпочитают использовать эту модель, принято считать что устройство HSB/HSV ближе к естественному восприятию цветов. В частности, цветовая модель HSB применяется в Adobe Photoshop.

HSB/HSV расшифровывается как Hue (цвет/оттенок), Saturation (насыщенность), Brightness/Value (яркость/значение).

Hue задаёт положение цвета на цветовом круге (от 0 до 360). Saturation является процентным значением насыщенности (от 0% до 100%). Brightness является процентным значением яркости (от 0% до 100%).

Цветовая модель XYZ (CIE 1931 XYZ) является чисто математическим пространством. В отличие от RGB, CMYK, и других моделей, в XYZ основные компоненты являются «мнимыми», то есть вы не можете соотнести X, Y, и Z с каким-либо набором цветов для смешивания. XYZ является мастер-моделью практически всех остальных цветовых моделей, используемых в технических областях.

Цветовая модель LAB (CIELAB, «CIE 1976 L*a*b*») вычисляется из пространства CIE XYZ. При разработке Lab преследовалась цель создания цветового пространства, изменение цвета в котором будет более линейным с точки зрения человеческого восприятия (по сравнению с XYZ), то есть с тем, чтобы одинаковое изменение значений координат цвета в разных областях цветового пространства производило одинаковое ощущение изменения цвета.

Источник

Convert hex color to RGB values in PHP

What would be a good way to convert hex color values like #ffffff into the single RGB values 255 255 255 using PHP?

17 Answers 17

If you want to convert hex to rgb you can use sscanf:

I made a function which also returns alpha if alpha is provided as a second parameter the code is below.

The function

Example of function responses

hex to hsl php. Смотреть фото hex to hsl php. Смотреть картинку hex to hsl php. Картинка про hex to hsl php. Фото hex to hsl php

For anyone that is interested this is another very simple way of doing it. This example assumes there is exactly 6 characters and no preceding pound sign.

Here is an example the supports 4 different inputs (abc, aabbcc, #abc, #aabbcc):

hex to hsl php. Смотреть фото hex to hsl php. Смотреть картинку hex to hsl php. Картинка про hex to hsl php. Фото hex to hsl php

You can use the function hexdec(hexStr: String) to get the decimal value of a hexadecimal string.

See below for an example:

This will print rgb(255, 255, 255)

hex to hsl php. Смотреть фото hex to hsl php. Смотреть картинку hex to hsl php. Картинка про hex to hsl php. Фото hex to hsl php

You can try this simple piece of code below.

This will return 123,222,132

hex to hsl php. Смотреть фото hex to hsl php. Смотреть картинку hex to hsl php. Картинка про hex to hsl php. Фото hex to hsl php

My approach to take care of hex colors with or without hash, single values or pair values:

Convert Color Code HEX to RGB

Output

I wrote a simple function like so, which supports an input value with or without beginning # and it can also take 3 or 6 character hex code input:

See also here from CSS Tricks.

I’ve put @John’s answer and @iic’s comment/idea together into a function which can handle both, the usual hex color codes and the shorthand color codes.

A short explanation:

Источник

hexdec

(PHP 4, PHP 5, PHP 7, PHP 8)

hexdec — Переводит число из шестнадцатеричной системы счисления в десятичную

Описание

hexdec() игнорирует любые обнаруженные не шестнадцатеричные символы. Начиная с PHP 7.4.0, предоставление любых некорректных символов устарело.

Список параметров

Шестнадцатеричная строка для преобразования

Возвращаемые значения

Десятичное представление hex_string

Список изменений

ВерсияОписание
7.4.0Передача некорректных символов будет выдавать уведомление об устаревании. Результат будет вычислен так, как если бы некорректные символы не существовали.

Примеры

Пример #1 Пример использования hexdec()

( hexdec ( «See» ));
var_dump ( hexdec ( «ee» ));
// в обоих случаях будет выведено «int(238)»

var_dump ( hexdec ( «that» )); // выведет «int(10)»
var_dump ( hexdec ( «a0» )); // выведет «int(160)»
?>

Примечания

Смотрите также

User Contributed Notes 31 notes

Use this function to convert a hexa decimal color code to its RGB equivalent. Unlike many other functions provided here, it will work correctly with hex color short hand notation.

Also, if a proper hexa decimal color value is given (6 digits), it uses bit wise operations for faster results.

For eg: #FFF and #FFFFFF will produce the same result

If you want to create or parse signed Hex strings:

Here is other function to transform a MAC Address to decimal:

Here’s my hexdec function for greater numbers using BC Math

After esnhexdec from «rledger at gmail dot com», the esndechex:

The issue I’ve seen with the existing hex to dec conversion routines is the lack of error-trapping. I stick to the theory that one should try to cover ALL the bases when writing a generalized routine such as this one. I have a varied background that covers a wide variety of design/development languages, on the web as well as desktop apps. As such I’ve seen multiple formats for writing hex colors.

For example, the color red COULD be written as follows:
#ff0000
&Hff0000
#ff
&Hff

Therefore I have written a function that is case-insensitive and takes into account the chance that different developers have a tendency to format hex colors in different ways.

/*
To use simply use the following function call:
$color = convert_color(«#FF»);
this will return the following assoc array if successful:
*[success] = true
*[r] = 255
*[g] = 0
*[b] = 0

or copy and paste the following code:

$hex = «FFFFFF»; // Color White
$color = convert_color($hex);
var_dump($color);
*/
?>

As you can see, the function «convert_color» accepts a hex # in most acceptable formats and returns an associative array. [success] is set to TRUE if the function succeeds and FALSE if not. The array members [r], [g] and [b] hold the red,green and blue values respectively. If it fails, [error] holds a custom error message.

«strip_chars» is a support function written to remove the unwanted characters from the hex string, and sends the concatenated string back to the calling function. It will accept either a single value or an array of values for the characters to remove.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *