php hex to rgb
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.
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:
Конвертировать hex цвет значения RGB в PHP
14 ответов
Существует ли функция php, которая возвращает ближайшее имя цвета, задавая цвет rgb или hex в качестве параметра? Я много обжегся, но не могу найти функцию, которая выполняла бы эту работу. Пожалуйста помочь
Если вы хотите преобразовать hex в rgb, вы можете использовать sscanf :
Я создал функцию, которая также возвращает альфа, если альфа указана в качестве второго параметра, код которого приведен ниже.
Функция
Пример ответов функций
Для всех, кто заинтересован, это еще один очень простой способ сделать это. В этом примере предполагается, что существует ровно 6 символов и нет предшествующего знака фунта.
Вот пример поддержки 4 различных входов (abc, aabbcc, #abc, #aabbcc):
Вы можете использовать функцию hexdec(hexStr: String) для получения десятичного значения шестнадцатеричной строки.
Это приведет к печати rgb(255, 255, 255)
Как я могу преобразовать цвет hex в код RGB в Java? В основном в Google есть примеры того, как конвертировать из RGB в hex.
Я хочу преобразовать hex цвет в RGB цвет. Я использовал следующий код: Me.BackColor = RGB(#000000) Но затем он выбрасывает следующее исключение: Argument not specified for parameter ‘Green’ of ‘Public Function RGB(Red As Integer, Green As Integer, Blue As Integer) As Integer’ Как правильно это.
Вы можете попробовать этот простой фрагмент кода ниже.
Это вернет 123 222 132
Мой подход к уходу за hex цветами с hash или без _30, одиночными значениями или парными значениями:
Преобразование цветового кода HEX в RGB
Выход
Я объединил @John’s ответов и @iic’s комментариев/идей в функцию, которая может обрабатывать как обычные hex цветовых кодов, так и сокращенные цветовые коды.
попробуйте это, он преобразует свои аргументы (r, g, b) в шестнадцатеричные html-цветная строка #RRGGBB Аргументы преобразуются в целые числа и обрезаются до диапазона 0..255
символ # в начале может быть опущен. Функция возвращает массив из трех целых чисел в диапазоне (0..255) или false, если она не распознает цветовой формат.
Это единственное решение, которое сработало для меня. Некоторые ответы были недостаточно последовательными.
Похожие вопросы:
Я пытаюсь создать крючок jQuery, который будет читать и устанавливать все цвета как значения hex вместо RGB. Я нашел крючок, который будет правильно читать цвет как HEX, но я не уверен, как изменить.
Ниже приведена функция преобразования цвета rgb в цвет hex. Но это не совсем правильно. С (0, 255, 0) (#00ff00). он возвращает ff00 и поэтому не является допустимым цветом. Мне нужна помощь, чтобы.
Я хочу конвертировать туда и обратно между RGBA-формированными HEX цветами (например, 0xFF0000FF ) и RGB-формированными HEX цветами (например, 0xFF0000 ) в PHP. Как я могу это сделать?
Существует ли функция php, которая возвращает ближайшее имя цвета, задавая цвет rgb или hex в качестве параметра? Я много обжегся, но не могу найти функцию, которая выполняла бы эту работу.
Как я могу преобразовать цвет hex в код RGB в Java? В основном в Google есть примеры того, как конвертировать из RGB в hex.
Я хочу преобразовать hex цвет в RGB цвет. Я использовал следующий код: Me.BackColor = RGB(#000000) Но затем он выбрасывает следующее исключение: Argument not specified for parameter ‘Green’ of.
Кто-нибудь знает функцию PHP (для >5.3), которая может преобразовать цвет HSL либо в RGB, либо в Hex? Я перепробовал дюжину поисковых запросов в Google, но ни одна из найденных мною функций не.
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:
*/
Convert HEX to RGB
Give function hex code (e.g. #eeeeee), returns array of RGB values.
Need front-end development training?
Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.
Need front-end development training?
Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.
Comments
Thanks, I used it as a good starting point.
I’ve updated it slightly to be shorter and with the assumption the end hex is always 6 characters (as I control the input). The str_split() might be helpful for your code maybe?
function($hexString) <
$hexString = preg_replace(“/[^abcdef]/i”,””,$hexString);
if(strlen($hexString)==6) <
list($r,$g,$b) = str_split($hexString,2);
return Array(“r”=>hexdec($r),”g”=>hexdec($g),”b”=>hexdec($b));
>
I just realised I didn’t copy the entire code.
There’s a false missing off the end! heh….
function hex2rgb($hexString) <
$hexString = preg_replace(“/[^abcdef]/i”,””,$hexString);
if(strlen($hexString)==6) <
list($r,$g,$b) = str_split($hexString,2);
return Array(“r”=>hexdec($r),”g”=>hexdec($g),”b”=>hexdec($b));
>
return false;
>
If anyone is interested in a javascript equivalent I used this (Not perfect but seems to do the job) :
function hex2rgb( colour ) <
var r,g,b;
if ( colour.charAt(0) == ‘#’ ) <
colour = colour.substr(1);
>
r = colour.charAt(0) + ” + colour.charAt(1);
g = colour.charAt(2) + ” + colour.charAt(3);
b = colour.charAt(4) + ” + colour.charAt(5);
Thanks its really working. With some modification it can also b used for rgba color code just adding one more parameter.
I want to say that this site has high quality content.
Of course, the code above, was just what I wanted.
thanks, you are a life saver. I needed this for a client project and had been playing for ages but I couldn’t get it quite right!