hex to hsv php
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.
Конвертер цветов
С помощью универсального конвертер цветов вы можете легко перевести цвет из одной цветовой модели в ряд других.
В первую очередь, калькулятор служит для удобной работы с современными форматами 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 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:
HSL to RGB:
Shortest
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.
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
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):
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)
You can try this simple piece of code below.
This will return 123,222,132
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:
dechex
(PHP 4, PHP 5, PHP 7, PHP 8)
dechex — Переводит число из десятичной системы счисления в шестнадцатеричную
Описание
Список параметров
Десятичное значение для преобразования
Так как тип PHP int является знаковым, а dechex() работает с беззнаковыми целыми, то отрицательные целые воспринимаются как беззнаковые.
Возвращаемые значения
Примеры
Пример #1 Пример использования dechex()
Результат выполнения данного примера:
Пример #2 Пример использования dechex() с большими целыми
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 33 notes
Be very careful calling dechex on a number if it’s stored in a string.
The max number it can handle is 4294967295 which in hex is FFFFFFFF, as it says in the documentation.
dechex(4294967295) => FFFFFFFF //CORRECT
BUT, if you call it on a string of a number, it casts to int, and automatically gives you the largest int it can handle.
dechex(‘4294967295’) => 7FFFFFFF //WRONG!
so you’ll need to cast to a float:
dechex((float) ‘4294967295’) => FFFFFFFF //CORRECT
This took me FOREVER to figure out, so hopefully I just saved someone some time.
Here are two functions that will convert large dec numbers to hex and vice versa. And I really mean LARGE, much larger than any function posted earlier.
now, here is a nice and small function to convert integers to hex strings and it avoids use of the DECHEX funtion because that function changed it’s behavior too often in the past (now, in PHP version 4.3.2 it works with numbers bigger than 0x7FFFFFFF correctly, but i need to be backward compatible).
Here is a very small zeropadding that you can use for numbers:
I was confused by dechex’s size limitation. Here is my solution to the problem. It supports much bigger values, as well as signs.
Easiest 😛 way to create random hex color:
Create Random Hex Color:
function rand_hex() <
mt_srand(make_seed());
$randval = mt_rand(0,255);
//convert to hex
return sprintf(«%02X»,$randval);
>
function random_color() <
return «#».rand_hex().rand_hex().rand_hex();
>
Here’s how to use bitwise operations for RGB2hex conversion. This function returns hexadesimal rgb value just like one submitted by gurke@bigfoot.com above.
function hexColor($color) <
return dechex(($color[0]
If you need to convert a large number (> PHP_MAX_INT) to a hex value, simply use base_convert. For example:
base_convert(‘2190964402’, 10, 16); // 829776b2
warning jbleau dec_to_hex method is buggy, avoid it.
I wrote this to convert hex into signed int, hope this helps someone out there. peace 🙂
If you want to create or parse signed Hex values:
I was challenged by a problem with large number calculations and conversion to hex within php. The calculation exceeded unsigned integer and even float range. You can easily change it for your needs but it is, thanks to bcmath, capable of handling big numbers via string. This function will convert them to hex.
In this specific example though, since I use it for game internals that can only handle 32 bit numbers, it will truncate calculations at 8 digits. If the input is 1 for example it will be filled up with zeros. Output 00000001h.
Of course I don’t claim it to be a good one, but it works for me and my purpose. Suggestions on faster code welcome!
To force the correct usage of 32-bit unsigned integer in some functions, just add ‘+0’ just before processing them.
These are functions to convert roman numbers (e.g. MXC) into dec and vice versa.
Note: romdec() does not check whether a string is really roman or not. To force a user-input into a real roman number use decrom(romdec($input)). This will turn XXXX into XL for example.
echo decrom ( romdec ( «XXXX» ));
?>
Warning for use on 64 bit machines! The Extra length matters!
so far it is ok. But for slightly bigger numbers:
note the difference!
This is particularly important when converting negative numbers:
If you want your code to be portable to amd64 or xeons (which are now quite popular with hosting companies) then you must ensure that your code copes with the different length of the result for negative numbers (and the max value, although that is probably less critical).
This function will take a string and convert it into a hexdump.
3c666f6e 74207369 7a653d22 33223e4c L
6561726e 20686f77 20746f20 62652061 earn.how.to.be.a
Here’s my version of a red->yellow->green gradient:
Here’s a function which works for decimal values up to 9007199254740992 (hex 20000000000000).
Heres a example of dec to html hex gradient. Have fun 🙂
//Amount of gradients
$l = 20;
//Start color
$start[0] = «255»; //red
$start[1] = «0»; //green
$start[2] = «255»; //blue
//End color
$end[0] = «255»; //red
$end[1] = «255»; //green
$end[2] = «255»; //blue
$rgb[$i] = dechex($rgb[$i]);
$rgb[$i] = strtoupper($rgb[$i]);
/*
here are two functions, some might find them useful (maybe for encoding)
converting string to hex and hex to string:
*/