Convert Hex To RGBA - Javascript - Stack Overflow
Có thể bạn quan tâm
-
- Home
- Questions
- Tags
- Users
- Companies
- Labs
- Jobs
- Discussions
- Collectives
-
Communities for your favorite technologies. Explore all Collectives
- Teams
Ask questions, find answers and collaborate at work with Stack Overflow for Teams.
Try Teams for free Explore Teams - Teams
-
Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about CollectivesTeams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about TeamsGet early access and see previews of new features.
Learn more about Labs Convert Hex to RGBA Ask Question Asked 10 years, 9 months ago Modified 7 months ago Viewed 204k times 140My fiddle - http://jsbin.com/pitu/1/edit
I wanted to try an easy hex to rgba conversion. Ever browser I've used renders colors using rgb as default so when using the farbtastic color picker I'm converting the hex value to rgb by grabbing the background color the hex value generates (as rgb by default = simple conversion)
I tried replacing the ) symbol to , 1), but that didn't work so I went to just see how converting rgb to rgba would work, and I'm still having trouble.
The jquery
$('.torgb').val($('#color').css('background-color')); $('.torgba').val().replace(/rgb/g,"rgba");The goal
EDIT:
TinyColor Is a great color manipulation js library that does everything I want here and more. I figure you guys may want to give it a try! - https://github.com/bgrins/TinyColor
Share Improve this question Follow edited May 22, 2018 at 0:04 Michael Schwartz asked Feb 8, 2014 at 13:43 Michael SchwartzMichael Schwartz 8,38514 gold badges86 silver badges151 bronze badges 1- 2 TinyColor Is a great color manipulation js library that does everything I want here and more. I figure you guys may want to give it a try! – Michael Schwartz Commented May 22, 2018 at 0:03
29 Answers
Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 239 //If you write your own code, remember hex color shortcuts (eg., #fff, #000) function hexToRgbA(hex){ var c; if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){ c= hex.substring(1).split(''); if(c.length== 3){ c= [c[0], c[0], c[1], c[1], c[2], c[2]]; } c= '0x'+c.join(''); return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)'; } throw new Error('Bad Hex'); } hexToRgbA('#fbafff') /* returned value: (String) rgba(251,175,255,1) */ Share Improve this answer Follow edited Jan 14, 2022 at 18:09 Top-Master 8,6345 gold badges47 silver badges85 bronze badges answered Feb 8, 2014 at 16:22 kennebeckennebec 105k32 gold badges108 silver badges127 bronze badges 3- 9 very easy to understand solution but it doesn't support 8 form hex like #ff0000aa? – supersan Commented Mar 25, 2019 at 17:43
- 1 This doesn't work if the input is not exactly 3 or 6 characters. – keeehlan Commented Jan 9, 2020 at 21:27
- 2 @KehlanKrumme What's your example? – Adrien Commented Apr 12, 2021 at 15:03
@ElDoRado1239 has the right idea, but there's also a cleaner way:
function hexToRGB(hex, alpha) { var r = parseInt(hex.slice(1, 3), 16), g = parseInt(hex.slice(3, 5), 16), b = parseInt(hex.slice(5, 7), 16); if (alpha) { return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")"; } else { return "rgb(" + r + ", " + g + ", " + b + ")"; } } hexToRGB('#FF0000', 0.5);
Share Improve this answer Follow edited Jun 20, 2017 at 19:01 answered Jan 20, 2015 at 23:10 AJFarkasAJFarkas 3,1391 gold badge18 silver badges15 bronze badges 8- 6 Note: this will fail on HEX shortcuts, e.g. #fff. That should be easily fixable though! – Matthew Herbst Commented Mar 21, 2017 at 21:51
- 1 Well, yes, you have to give the function the correct input… – AJFarkas Commented Mar 22, 2017 at 22:14
- 2 Very readable, I like it much more than the reg exp based solution. – dahrens Commented Oct 17, 2017 at 13:22
- Nice work!! A little thing I have to mention though. I have some bad experience of keeping spaces between comma and the RGBA values in the string. (eg: rgba(255, 35, 234, 0.5)). Especially if you pass this value to another program, be aware of that. Because there some programs which does not accept spaces between values in the string. So, better to remove those spaces from final output. – Tharanga Commented Oct 31, 2017 at 20:00
- eslint is just style enforcement. It's only by chance that nothing I wrote contradicts your style preferences. In fact this would not pass linting on the project I'm currently working on, for instance. – AJFarkas Commented May 17, 2019 at 21:43
ES6 function for only handling 6 character hex with or without the '#':
const hex2rgba = (hex, alpha = 1) => { const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16)); return `rgba(${r},${g},${b},${alpha})`; };Usage:
hex2rgba('#af087b', .5) // returns: rgba(175,8,123,0.5) hex2rgba('af087b', .5) // returns: rgba(175,8,123,0.5) hex2rgba('af087b') // returns: rgba(175,8,123,1) Share Improve this answer Follow edited Aug 23, 2018 at 20:13 dǝɥɔS ʇoıןןƎ 1,8005 gold badges23 silver badges45 bronze badges answered Jul 27, 2018 at 19:55 Lobster FighterLobster Fighter 7586 silver badges7 bronze badges 3- Since toString on Array joins with , and the fact input can be rrggbbaa hex you can change it to const rgb = hex.match(...).slice(0,3).map(...) returnn`${rgb},${alpha}`; – Morteza Tourani Commented Mar 10, 2019 at 11:58
- 1 below code will also convert hex2rgba('#369', 0.5); var hex2rgba = (hex, alpha = 1) => { const [r, g, b] = hex.match(hex.length<=4 ? /\w/g : /\w\w/g).map(x => parseInt(x.length<2?${x}${x}: x, 16)); return rgba(${r},${g},${b},${alpha}); }; – Serkan KONAKCI Commented Dec 13, 2019 at 11:21
- I would suggest using hex.match(/[0-9A-Fa-f]{2}/g) to make sure the input is hex chars only – Barlo Commented Oct 31, 2022 at 14:04
Clean TypeScript version:
hexToRGB(hex: string, alpha: string) { const r = parseInt(hex.slice(1, 3), 16); const g = parseInt(hex.slice(3, 5), 16); const b = parseInt(hex.slice(5, 7), 16); if (alpha) { return `rgba(${r}, ${g}, ${b}, ${alpha})`; } return `rgb(${r}, ${g}, ${b})`; }Based on @AJFarkas's answer.
Share Improve this answer Follow edited Aug 25, 2021 at 12:45 answered Nov 9, 2017 at 12:12 ChrillewoodzChrillewoodz 28.2k23 gold badges99 silver badges183 bronze badges 5- 3 This doesn't work everytime in some cases it returns NaN for r, g or/and b. – Renascent Commented Apr 30, 2019 at 12:45
- Worked out for me! Thx – Saxophonist Commented Jul 9, 2020 at 16:43
- shouldn't the else return rgb(${r}, ${g}, ${b}) since it won't have an alpha? – Amanshu Kataria Commented Nov 30, 2020 at 10:28
- @AmanshuKataria Yes it should. Good spot. – Chrillewoodz Commented Nov 30, 2020 at 12:45
- 1 No need for else {} since you returning in if. Also consider one-liner: return alpha ? `rgba(${r}, ${g}, ${b}, ${alpha})` : `rgb(${r}, ${g}, ${b})` – Sebastian Vorac Commented Apr 12, 2021 at 18:53
Any Hex Form Modular Approach
The main challenge is that as of 2018 there are a few forms of HEX. The 6 char traditional form, the 3 char shorten form, and a new 4 and 8 char form that includes alpha. The following function can handle any HEX form.
const isValidHex = (hex) => /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(hex) const getChunksFromString = (st, chunkSize) => st.match(new RegExp(`.{${chunkSize}}`, "g")) const convertHexUnitTo256 = (hexStr) => parseInt(hexStr.repeat(2 / hexStr.length), 16) const getAlphafloat = (a, alpha) => { if (typeof a !== "undefined") {return a / 255} if ((typeof alpha != "number") || alpha <0 || alpha >1){ return 1 } return alpha } export const hexToRGBA = (hex, alpha) => { if (!isValidHex(hex)) {throw new Error("Invalid HEX")} const chunkSize = Math.floor((hex.length - 1) / 3) const hexArr = getChunksFromString(hex.slice(1), chunkSize) const [r, g, b, a] = hexArr.map(convertHexUnitTo256) return `rgba(${r}, ${g}, ${b}, ${getAlphafloat(a, alpha)})` }Alpha could be provided to the function in the following ways:
- As part of a 4, or 8 form HEX .
- As a second parameter between 0-1,
OutPut
const c1 = "#f80" const c2 = "#f808" const c3 = "#0088ff" const c4 = "#0088ff88" const c5 = "#98736" console.log(hexToRGBA(c1)) // rgba(255, 136, 0, 1) console.log(hexToRGBA(c2)) // rgba(255, 136, 0, 0.53125) console.log(hexToRGBA(c3)) // rgba(0, 136, 255, 1) console.log(hexToRGBA(c4)) // rgba(0, 136, 255, 0.53125) console.log(hexToRGBA(c5)) // Uncaught Error: Invalid HEX console.log(hexToRGBA(c1, 0.5)) // rgba(255, 136, 0, 0.5) console.log(hexToRGBA(c3, 0.5)) // rgba(0, 136, 255, 0.5) Share Improve this answer Follow edited Jul 10, 2020 at 17:58 answered Dec 26, 2018 at 20:06 Ben CarpBen Carp 26.3k11 gold badges65 silver badges82 bronze badges 5- 2 Some browsers support Hex colours with opacity, other do not. This answer was very useful in converting 8 form hex to rgba, rgba being supported in all browsers. – George Commented Aug 31, 2019 at 16:34
- 2 @George, Thanks! After creating this I asked myself if such a comprehensive approach is actually necessary. Your feedback is valuable. – Ben Carp Commented Sep 1, 2019 at 3:03
- 1 I think there might be 1 tiny bug in the alpha calc. I think it should read: return a / 255 otherwise FF doesn't return 1 – Dustin Kerstein Commented Jul 10, 2020 at 14:37
- @DustinKerstein nice catch! Probably can't do harm, but still should be fixed. – Ben Carp Commented Jul 10, 2020 at 17:18
- 1 This is the best answer and it worked for me with all unit tests. – Ala Eddine Menai Commented Sep 14, 2020 at 16:21
Pure JS solution if it helps:
function hexToRGB(hex,alphaYes){ var h = "0123456789ABCDEF"; var r = h.indexOf(hex[1])*16+h.indexOf(hex[2]); var g = h.indexOf(hex[3])*16+h.indexOf(hex[4]); var b = h.indexOf(hex[5])*16+h.indexOf(hex[6]); if(alphaYes) return "rgba("+r+", "+g+", "+b+", 1)"; else return "rgb("+r+", "+g+", "+b+")"; }"alphaYes" is "true" or "false" depending upon whether you want the alpha or not.
Share Improve this answer Follow edited Feb 8, 2014 at 14:01 answered Feb 8, 2014 at 13:51 ElDoRado1239ElDoRado1239 4,0382 gold badges17 silver badges13 bronze badges 3- The else keyword is unnecessary in this case. It will return the non-alpha regardless. – Andy Commented Feb 8, 2014 at 13:55
- Oh, yeah, but this seems more "tidy" to me. Just a matter of personal preference I guess. – ElDoRado1239 Commented Feb 8, 2014 at 14:02
- 1 This code doesn't work with lowercase hex (eg. #f0a16e). I suggest to convert hex with toUpperCase first. – philippe_b Commented Feb 12, 2016 at 10:40
Here is a function that returns rgb or rgba if you provide an alpha. The function also converts short hex color codes too.
function:
function hexToRgb(hex, alpha) { hex = hex.replace('#', ''); var r = parseInt(hex.length == 3 ? hex.slice(0, 1).repeat(2) : hex.slice(0, 2), 16); var g = parseInt(hex.length == 3 ? hex.slice(1, 2).repeat(2) : hex.slice(2, 4), 16); var b = parseInt(hex.length == 3 ? hex.slice(2, 3).repeat(2) : hex.slice(4, 6), 16); if ( alpha ) { return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')'; } else { return 'rgb(' + r + ', ' + g + ', ' + b + ')'; } }examples:
hexToRgb('FF0000');// rgb(255, 0, 0) hexToRgb('#FF0000');// rgb(255, 0, 0) hexToRgb('#FF0000', 1);// rgba(255, 0, 0, 1) hexToRgb('F00');// rgb(255, 0, 0) hexToRgb('#F00');// rgb(255, 0, 0) hexToRgb('#F00', 1);// rgba(255, 0, 0, 1) Share Improve this answer Follow answered Jul 2, 2017 at 10:55 TURTLETURTLE 3,8474 gold badges52 silver badges53 bronze badges Add a comment | 9ES6 modern, RegEx free, solution with error checking and constant arrow function, that returns null for errors. If alpha is not given then the default value of one is used:
const hexToRGB = (hex, alpha = 1) => { let parseString = hex; if (hex.startsWith('#')) {parseString = hex.slice(1, 7);} if (parseString.length !== 6) {return null;} const r = parseInt(parseString.slice(0, 2), 16); const g = parseInt(parseString.slice(2, 4), 16); const b = parseInt(parseString.slice(4, 6), 16); if (isNaN(r) || isNaN(g) || isNaN(b)) {return null;} return `rgba(${r}, ${g}, ${b}, ${alpha})`; };Note: It returns null for errors. You may replace {return null;} with a throw statement: {throw "Not a valid hex color!";}, but then you should call it from within try-catch:
hexToRGB("#3454r5") => null hexToRGB("#345465") => rgba(52, 84, 101, 1) hexToRGB("#345465", 0.5) => rgba(52, 84, 101, 0.5) Share Improve this answer Follow edited Jul 31, 2018 at 10:44 answered May 24, 2018 at 14:36 SverrissonSverrisson 18.1k5 gold badges68 silver badges65 bronze badges Add a comment | 6Here's a quick function that supports 3, 4, 6 and 8 character color codes:
function hexToRGBA(hex) { // remove invalid characters hex = hex.replace(/[^0-9a-fA-F]/g, ''); if (hex.length < 5) { // 3, 4 characters double-up hex = hex.split('').map(s => s + s).join(''); } // parse pairs of two let rgba = hex.match(/.{1,2}/g).map(s => parseInt(s, 16)); // alpha code between 0 & 1 / default 1 rgba[3] = rgba.length > 3 ? parseFloat(rgba[3] / 255).toFixed(2): 1; return 'rgba(' + rgba.join(', ') + ')'; }Here's what it does. It removes any non-hexadecimal characters. If the HEX is shorter than 5 (3 or 4) characters, it doubles each character. It then splits the HEX into pairs of two characters and parses each pair to an integer. If there is an alpha HEX, it's parsed to a float from 0 to 1, otherwise it's defaulted to 1. The RGBA string is then formed by joining the array and returned.
Share Improve this answer Follow edited Nov 27, 2020 at 14:59 answered Nov 27, 2020 at 14:53 Jacques MaraisJacques Marais 2,75618 silver badges34 bronze badges 0 Add a comment | 5I liked the @AJFarkas answer and append the support for shortcut hex (#fff) to it
function hexToRGB(hex, alpha) { if (!hex || [4, 7].indexOf(hex.length) === -1) { return; // throw new Error('Bad Hex'); } hex = hex.substr(1); // if shortcuts (#F00) -> set to normal (#FF0000) if (hex.length === 3) { hex = hex.split('').map(function(el){ return el + el + ''; }).join(''); } var r = parseInt(hex.slice(0, 2), 16), g = parseInt(hex.slice(2, 4), 16), b = parseInt(hex.slice(4, 6), 16); if (alpha !== undefined) { return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")"; } else { return "rgb(" + r + ", " + g + ", " + b + ")"; } } document.write(hexToRGB('#FF0000', 0.5)); document.write('<br>'); document.write(hexToRGB('#F00', 0.4));
Share Improve this answer Follow edited Mar 12, 2018 at 12:54 Willem 7871 gold badge7 silver badges10 bronze badges answered Jun 14, 2017 at 16:32 Peter DenevPeter Denev 5514 silver badges11 bronze badges Add a comment | 4A clean and readable typescript way: (I could separate type, but it's easier to copy past like that)
export const hexToRGB = (hex: string, alpha: number | undefined = 1) => { hex = hex.toUpperCase(); const r = parseInt(hex.slice(1, 3), 16); const g = parseInt(hex.slice(3, 5), 16); const b = parseInt(hex.slice(5, 7), 16); return `rgba(${r}, ${g}, ${b}, ${alpha})`; } Share Improve this answer Follow answered Aug 15, 2022 at 18:18 Guillaume Huard HughesGuillaume Huard Hughes 1631 silver badge8 bronze badges Add a comment | 3Here's an ES2015+ version that's a little more defensive and handles the shorthand 3-digit syntax.
/* * Takes a 3 or 6-digit hex color code, and an optional 0-255 numeric alpha value */ function hexToRGB(hex, alpha) { if (typeof hex !== 'string' || hex[0] !== '#') return null; // or return 'transparent' const stringValues = (hex.length === 4) ? [hex.slice(1, 2), hex.slice(2, 3), hex.slice(3, 4)].map(n => `${n}${n}`) : [hex.slice(1, 3), hex.slice(3, 5), hex.slice(5, 7)]; const intValues = stringValues.map(n => parseInt(n, 16)); return (typeof alpha === 'number') ? `rgba(${intValues.join(', ')}, ${alpha})` : `rgb(${intValues.join(', ')})`; } Share Improve this answer Follow edited Jun 25, 2018 at 18:43 Paweł Gościcki 9,5645 gold badges73 silver badges82 bronze badges answered May 10, 2018 at 22:31 GeoffGeoff 4854 silver badges6 bronze badges Add a comment | 3function hexToRGB(hex, alpha) { var r = parseInt(hex.slice(1, 3), 16), g = parseInt(hex.slice(3, 5), 16), b = parseInt(hex.slice(5, 7), 16); if (alpha) { return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")"; } else { return "rgb(" + r + ", " + g + ", " + b + ")"; } } hexToRGB('#FF0000', 0.5);
Share Improve this answer Follow answered Mar 21, 2021 at 14:09 Hovik GhambaryanHovik Ghambaryan 313 bronze badges 1- Simple and short, thanks! For a 1-liner and to return the result as array (assuming no alpha is needed, like in my case), this can be used: return [parseInt(hex.slice(1, 3), 16), parseInt(hex.slice(3, 5), 16), parseInt(hex.slice(5, 7), 16)]; – yenren Commented Jan 6, 2022 at 8:45
Actually, I like to use ES6 methods alongside preventing myself to using RegExp, RegExp is not safe, I don't trust it, the below answer is TypeScript, if you only need JavaScript just remove types:
// TypeScript const hex2rgba = (hex: string, alpha = 1): string => { if (alpha > 1 || alpha < 0) { throw new Error('alpha is not correct!'); } const red = parseInt(hex.slice(1, 3), 16); const green = parseInt(hex.slice(3, 5), 16); const blue = parseInt(hex.slice(5, 7), 16); return `rgba(${red}, ${green}, ${blue}, ${alpha})`; }; Share Improve this answer Follow answered Aug 2, 2021 at 19:05 AmerllicAAmerllicA 32.2k17 gold badges142 silver badges166 bronze badges Add a comment | 2After so many years, just for the record, the DOM API does this convertion by default including the alpha. I mean if you do like;
tempElement.style.cssText = "color: #de1e7eaa"; console.log(tempElement.style.color) // <- rgb(222, 30, 126, 0.667)you get RGB values as a string. Then you may or not process it according to your needs. We can leverage this opportunity if we are lazy enough.
var color = "#de1e7eaa", // hex color code in string including alpha temp = document.createElement("i"), // just a temporary element rgbStr, rgbInt; temp.style.cssText = `color: ${color}`; // assign it to the style of the <i> element rgbStr = temp.style.color; rgbInt = Array.from(rgbStr.matchAll(/\d+\.?\d*/g), c=> +c[0]) // temp.style.color gives RGB string // then we convert it to Number if need be console.log(rgbStr); console.log(rgbInt);
Share Improve this answer Follow edited Jan 14, 2022 at 19:15 answered Jan 14, 2022 at 18:32 ReduRedu 26.1k6 gold badges60 silver badges81 bronze badges Add a comment | 2It's likely overkill for most use cases, but if you need a solution that handles every edge case including all named colors, and actually converts any valid CSS color string (not just hex) to RGBA:
function toRGBA(cssColor) { let el = document.createElement("div"); el.style.color = cssColor; el.style.display = "none"; document.body.appendChild(el); let rgba = window.getComputedStyle(el).getPropertyValue("color"); el.remove(); let [r, g, b, a] = rgba.match(/[0-9.]+/g).map(n => Number(n)); if(a === undefined) a = 1; // <-- getPropertyValue returns rgb(...) if there is no transparency, so we add alpha if missing return [r, g, b, a]; } toRGBA("#34f1a8") // [52, 241, 168, 1] toRGBA("#fe6") // [255, 238, 102, 1] toRGBA("blue") // [0, 0, 255, 1] toRGBA("hsl(0, 90%, 50%)") // [242, 13, 13, 1] ...(Obviously this approach is not appropriate for server-side code like Deno or Node.js)
Share Improve this answer Follow answered Nov 11, 2022 at 21:15 joejoe 5,3132 gold badges47 silver badges53 bronze badges Add a comment | 1And another one based around bit shifting.
// hex can be a string in the format of "fc9a04", "0xfc9a04" or "#fc90a4" (uppercase digits are allowed) or the equivalent number // alpha should be 0-1 const hex2rgb = (hex, alpha) => { const c = typeof(hex) === 'string' ? parseInt(hex.replace('#', ''), 16) : hex; return `rgb(${c >> 16}, ${(c & 0xff00) >> 8}, ${c & 0xff}, ${alpha})`; }; Share Improve this answer Follow edited Jun 5, 2019 at 16:09 answered Jun 5, 2019 at 15:58 nitzelnitzel 1,81516 silver badges15 bronze badges Add a comment | 1Try
let hex2rgba= (hex,a)=> `rgba(${hex.substr(1).match(/../g).map(x=>+`0x${x}`)},${a})`/// hex - str e.g. "#abcdef"; a - alpha range 0-1; result e.g. "rgba(1,1,1,0)" let hex2rgba= (hex,a)=> `rgba(${hex.substr(1).match(/../g).map(x=>+`0x${x}`)},${a})`; function convert() { console.log(hex2rgba(inp.value,1)); } <input id="inp" value="#abcdef" > <button onclick="convert()">convert</button>
Share Improve this answer Follow edited Sep 25, 2021 at 7:59 answered Oct 15, 2019 at 7:50 Kamil KiełczewskiKamil Kiełczewski 91.7k34 gold badges394 silver badges366 bronze badges 2- you need to update rgb to rgba in the return 😉 – Alexander Cherednichenko Commented Sep 25, 2021 at 5:53
- @AlexanderCherednichenko you are right - thank you - fixed – Kamil Kiełczewski Commented Sep 25, 2021 at 8:01
Modifying @kennebec's solution to have alpha parameter
function hexToRgbA(hex, alpha=1){ if(alpha > 1) alpha = 1; if(alpha < 0) alpha = 0; var c; if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){ c= hex.substring(1).split(''); if(c.length== 3){ c= [c[0], c[0], c[1], c[1], c[2], c[2]]; } c= '0x'+c.join(''); return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+','+alpha+')'; } throw new Error('Bad Hex'); } hexToRgbA('#fce881', 0.6); /* returned value: (String) rgba(252,232,129,0.6) */ Share Improve this answer Follow answered Apr 20, 2022 at 9:04 aphoeaphoe 2,7161 gold badge30 silver badges32 bronze badges Add a comment | 1Works with all shortcuts
Based on @kennebec's answer, here is a solution which works with all hex shortcuts (#123, #1234, #123456, #12345678).
const hex2rgba = (hex) => { let c = hex.substring(1).split(''); if (!/^#(([\dA-Fa-f]{3}){1,2}|([\dA-Fa-f]{4}){1,2})$/.test(hex)) { throw new Error('Your hexadecimal color is not correct.'); } switch (c.length) { case 3: c = [c[0] + c[0], c[1] + c[1], c[2] + c[2], 'ff']; break; case 4: c = [c[0]+c[0], c[1]+c[1], c[2]+c[2], c[3]+c[3]]; break; case 6: c = [c[0]+c[1], c[2]+c[3], c[4]+c[5], 'ff']; break; case 8: c = [c[0]+c[1], c[2]+c[3], c[4]+c[5], c[6]+c[7]]; break; } c = c.map((char) => parseInt(char, 16).toString()); c[3] = (Math.round((parseInt(c[3],10)/255)*100)/100).toString(); return c[3] === '1' ? `rgb( ${c[0]}, ${c[1]}, ${c[2]})` : `rgba(${c[0]}, ${c[1]}, ${c[2]}, ${c[3]})`; } //return a rgb or rgba value according to the alpha value console.log(hex2rgba('#af6')) console.log(hex2rgba('#af6f')) console.log(hex2rgba('#af64f576'))
Typescript Version
const hex2rgba = (hex: string): string => { let c: string[] = hex.substring(1).split(''); if (!/^#(([\dA-Fa-f]{3}){1,2}|([\dA-Fa-f]{4}){1,2})$/.test(hex)) { throw new Error('Your hexadecimal color is not correct.'); } switch (c.length) { case 3: c = [c[0] + c[0], c[1] + c[1], c[2] + c[2], 'ff']; break; case 4: c = [c[0]+c[0], c[1]+c[1], c[2]+c[2], c[3]+c[3]]; break; case 6: c = [c[0]+c[1], c[2]+c[3], c[4]+c[5], 'ff']; break; case 8: c = [c[0]+c[1], c[2]+c[3], c[4]+c[5], c[6]+c[7]]; break; } c = c.map((char) => parseInt(char, 16).toString()); c[3] = (Math.round((parseInt(c[3],10)/255)*100)/100).toString(); return c[3] === '1' ? `rgb( ${c[0]}, ${c[1]}, ${c[2]})` : `rgba(${c[0]}, ${c[1]}, ${c[2]}, ${c[3]})`; }
Share Improve this answer Follow answered May 22, 2022 at 16:09 arnaudpfarnaudpf 781 silver badge5 bronze badges Add a comment | 0Convert HEX with alpha (ahex) in to rgba.
function ahex_to_rba(ahex) { //clean # ahex = ahex.substring(1, ahex.length); ahex = ahex.split(''); var r = ahex[0] + ahex[0], g = ahex[1] + ahex[1], b = ahex[2] + ahex[2], a = ahex[3] + ahex[3]; if (ahex.length >= 6) { r = ahex[0] + ahex[1]; g = ahex[2] + ahex[3]; b = ahex[4] + ahex[5]; a = ahex[6] + (ahex[7] ? ahex[7] : ahex[6]); } var int_r = parseInt(r, 16), int_g = parseInt(g, 16), int_b = parseInt(b, 16), int_a = parseInt(a, 16); int_a = int_a / 255; if (int_a < 1 && int_a > 0) int_a = int_a.toFixed(2); if (int_a || int_a === 0) return 'rgba('+int_r+', '+int_g+', '+int_b+', '+int_a+')'; return 'rgb('+int_r+', '+int_g+', '+int_b+')'; }Try it yourself with snippet:
function ahex_to_rba(ahex) { //clean # ahex = ahex.substring(1, ahex.length); ahex = ahex.split(''); var r = ahex[0] + ahex[0], g = ahex[1] + ahex[1], b = ahex[2] + ahex[2], a = ahex[3] + ahex[3]; if (ahex.length >= 6) { r = ahex[0] + ahex[1]; g = ahex[2] + ahex[3]; b = ahex[4] + ahex[5]; a = ahex[6] + (ahex[7] ? ahex[7] : ahex[6]); } var int_r = parseInt(r, 16), int_g = parseInt(g, 16), int_b = parseInt(b, 16), int_a = parseInt(a, 16); int_a = int_a / 255; if (int_a < 1 && int_a > 0) int_a = int_a.toFixed(2); if (int_a || int_a === 0) return 'rgba('+int_r+', '+int_g+', '+int_b+', '+int_a+')'; return 'rgb('+int_r+', '+int_g+', '+int_b+')'; } $(function() { $('#go').click(function() { $('p b').text(ahex_to_rba($('#hex').val())); }) }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="hex" type="text" value="#ffaaffaa"> <input id="go" type="button" value="Go"> <p>Result: <b></b></p>
Original Author
Share Improve this answer Follow edited Oct 19, 2019 at 10:38 answered Oct 19, 2019 at 10:08 fdrvfdrv 8601 gold badge12 silver badges21 bronze badges Add a comment | 0Adding to @ElDoRado1239
For those that want to pass alpha value (typescript snippet):
static hexToRGB(hex: string, alpha: number): string { var h = "0123456789ABCDEF"; var r = h.indexOf(hex[1]) * 16 + h.indexOf(hex[2]); var g = h.indexOf(hex[3]) * 16 + h.indexOf(hex[4]); var b = h.indexOf(hex[5]) * 16 + h.indexOf(hex[6]); if (alpha) { return `rgba(${r}, ${g}, ${b}, ${alpha})` } return `rgba(${r}, ${g}, ${b})`; } Share Improve this answer Follow edited May 7, 2020 at 15:29 answered May 7, 2020 at 14:34 LeoLeo 3113 silver badges5 bronze badges Add a comment | 0This should work for all use cases (short codes, long codes, with/without alpha)
hexToRGBA=q=>{ q=q.replace('#', '') let l=q.length if(l!=3 && l!=4 && l!==6 && l!=8) return let red, green, blue, alpha, red_, green_, blue_, alpha_ switch(l){ case 3: red_ = q[0]+q[0] green_ = q[1]+q[1] blue_ = q[2]+q[2] alpha = 255 break case 4: red_ = q[0]+q[0] green_ = q[1]+q[1] blue_ = q[2]+q[2] alpha_ = q[3]+q[3] alpha = +("0x"+alpha_) break case 6: red_ = q[0]+q[1] green_ = q[2]+q[3] blue_ = q[4]+q[5] alpha = 255 break case 8: red_ = q[0]+q[1] green_ = q[2]+q[3] blue_ = q[4]+q[5] alpha_ = q[6]+q[7] alpha = +("0x"+alpha_) break } red = +("0x"+red_) green = +("0x"+green_) blue = +("0x"+blue_) return [red, green, blue, alpha] }note: alpha is returned as the 4th element, range 0-255
Share Improve this answer Follow answered Aug 7, 2022 at 14:15 cantelopecantelope 1,1657 silver badges9 bronze badges Add a comment | 0 function* chunks(array, size) { for (let i = 0; i < array.length; i += size) { yield array.slice(i, i + size); } } function hexToRgba(hex, opacity = 1) { const arr = hex.replace("#", "").split(""); return [...chunks(arr, arr.length === 6 ? 2 : 1)].reduce( (accum, cv, index, array) => { const lastIndex = array.length - 1 === index; const int = parseInt( array.length === 2 ? cv.join("") : cv[0] + cv[0], 16 ); return accum + int + (lastIndex ? `,${opacity})` : ","); }, "rgba(" ); } console.log(hexToRgba("#eee", 1));With a generator and reduce. Can be used with or without a #.
Share Improve this answer Follow edited Oct 18, 2022 at 23:10 answered Oct 18, 2022 at 21:55 Riza KhanRiza Khan 3,1085 gold badges28 silver badges59 bronze badges Add a comment | 0A one-liner if you only need to handle the simple case (i.e. doesn't handle shortcuts like #fff):
"aabbcc".split(/(..)/).filter(c=>c).map(c => parseInt(c, 16)) Share Improve this answer Follow edited Nov 11, 2022 at 21:16 answered Oct 30, 2022 at 12:47 joejoe 5,3132 gold badges47 silver badges53 bronze badges Add a comment | 0Hope this helps
function hexToRGBA(hex = '', alpha = 1) { const hexValue = hex.replace(/^#/, ''); let r = 0; let g = 0; let b = 0; let a = alpha; // Handle Hex Shorthand if ([3, 4].includes(hexValue.length)) { r = parseInt(`${hexValue[0].repeat(2)}`, 16); g = parseInt(`${hexValue[1].repeat(2)}`, 16); b = parseInt(`${hexValue[2].repeat(2)}`, 16); // Handle when We've opacity in hex if (typeof hexValue[3] !== 'undefined') { a = (parseInt(`${hexValue[3].repeat(2)}`, 16) / 255).toFixed(2) ?? 0; } // If hex is either of length 6, or 8 get rgba } else if ([6, 8].includes(hexValue.length)) { r = parseInt(`${hexValue.slice(0, 2)}`, 16); g = parseInt(`${hexValue.slice(2, 4)}`, 16); b = parseInt(`${hexValue.slice(4, 6)}`, 16); // Handle when We've opacity in hex if (hexValue.slice(6, 8).length !== 0) { a = (parseInt(`${hexValue.slice(6, 8)}`, 16) / 255).toFixed(2) ?? 0; } } return `rgba(${r}, ${g}, ${b}, ${a})`; } console.log(hexToRGBA('#aaaa')) // => rgba(127, 17, 224, 1)
Share Improve this answer Follow edited Apr 15 at 13:17 Cristik 32.8k25 gold badges99 silver badges139 bronze badges answered Apr 12 at 17:49 NOVELNOVEL 263 bronze badges Add a comment | -1No need to re-implement the wheel:
- RGB to HEX: https://github.com/sindresorhus/rgb-hex
- HEX to RGB: https://github.com/sindresorhus/hex-rgb
- sometimes redesigning a wheel gives you a smoother ride... – James Walker Commented Jan 19, 2022 at 0:30
- 1 that's what wheel designers would say.. :D – thisismydesign Commented Jan 19, 2022 at 10:15
- No need to take a sledgehammer to crack a nut... – EMiDU Commented Mar 22, 2022 at 9:43
I'm just gonna put this right here:
(str, alpha) => { if(!/^#([A-Fa-f0-9]{3}){1,2}$/.test(str)) throw new Error('Bad hex') let c = str.substring(1).split('') if(c.length === 3) c = [c[0], c[0], c[1], c[1], c[2], c[2]]; c = '0x'+c.join(''); return `rgba(${(c>>16)&255}, ${(c>>8)&255}, ${c&255}, ${alpha})`; }; Share Improve this answer Follow answered Mar 9, 2021 at 4:03 jujiyangaslijujiyangasli 3604 silver badges13 bronze badges Add a comment | -11Try This
<div class="torgb" onclick="rgba();" style="background-color:#000; width:20px; height:20px;"></div> <script> function rgba(){ $('.torgb').attr('background-color','rgba(0,0,0,1)'); $('.torgb').attr('onclick','hex();'); } function hex(){ $('.torgb').attr('background-color','#000'); $('.torgb').attr('onclick','rgba();'); } </script> Share Improve this answer Follow answered Feb 8, 2014 at 13:54 napster3worldnapster3world 3661 gold badge2 silver badges9 bronze badges 1- Where are the hex and rgba functions coming from? – Andy Commented Feb 8, 2014 at 13:58
Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Draft saved Draft discardedSign up or log in
Sign up using Google Sign up using Email and Password SubmitPost as a guest
Name EmailRequired, but never shown
Post Your Answer DiscardBy clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Not the answer you're looking for? Browse other questions tagged
or ask your own question.- The Overflow Blog
- Your docs are your infrastructure
- Featured on Meta
- More network sites to see advertising test [updated with phase 2]
- We’re (finally!) going to the cloud!
- Call for testers for an early access release of a Stack Overflow extension...
Linked
-2 Convert 6 digit hex colors to 6 digit hex color based on opacity value 261 How to set background color of view transparent in React Native 17 How to add transparency to a value from a HTML input type color field in CSS? 2 jQuery convert hex to rgba -1 JavaScript normalise CSS color values (convert to hex?) 0 Hex to rgb converter in javascript 1 How can I use transparent background if I get color code as hex number from fire base 0 HTML5 or CSS use ARGB instead of RGBA 1 Javascript Canvas not Updating Correctly on Form Change 0 Highcharts auto calculate gradient values for a color See more linked questionsRelated
209 How to get hex color value rather than RGB value? 1 Convert RGB to Hex color 4 HEX to RGB Converter 30 Convert rgb strings to hex in Javascript 2 How do I convert RGB decimal to Hex colors in JavaScript? 2 jQuery convert hex to rgba 18 How to convert RGBA to Hex color code using javascript 0 RGBA and RGB to Hex 6 how can i convert rgb value to hex color using jquery? 0 Getting Hex from RGBA in jsHot Network Questions
- How do I find out what kind of access a user has to a SharePoint Online site using PNP PowerShell?
- Lebesgue equivalence class with no continuous representative
- Identifying a TNG episode where Dr. Pulaski instructs another doctor on a sling
- How can I avoid overusing her/she or the character name when describing character action
- Table structure with multiple foreign keys and values
- Weapon Mastery and Weapon Cantrips
- In GR, what is Gravity? A force or curvature of spacetime?
- What exactly is the cornerstone that Mark 12:10 speaks of?
- Can you make 5 x 3 “magic” rectangles?
- If the hard problem of consciousness is unanswerable, is it a hard problem or just a bad question?
- It will not last
- Do I need Letter of invitation to Iceland?
- Solving Large size problems in industry: Tips and Tricks
- Find the Smallest Data Type for a Number
- Why didn't Steve Zahn receive a credit for Silo?
- Mega Man: Powered Up
- How to say "Each one of the following" in German?
- Comedy/Sci-Fi movie about one of the last men on Earth living in a museum/zoo on display for humanoid robots
- If someone’s words are likely to be disregarded, how to describe the quality of “meaning” they lack?
- Special stairs of infinites and infinitesimals
- Can you please advise on kerning?
- What powers do police have to force people onto trains?
- What is small arch between two notes and how to play it?
- How important is storytelling when submitting a grant application (or even a science paper)?
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
lang-jsTừ khóa » Html To Rgba Converter
-
HEX 2 RGBA Color Calculator | By @Devoth
-
RGBA And Hex Color Converter - CSS Generator Tool
-
Color Converter - W3Schools
-
Color To Hex And Rgba Converter - Popular Blocks
-
Hex To RGBA Converter Online Tool
-
HTML Color Codes - What's Your Color
-
Convert HTML To RGBA / URL To RGBA (Online & Free) - Convertio
-
RGBA To HEX Converter - Simple CSS Media Query Generator
-
HEX To RGBA Converter Online - 10015 Tools
-
How To Convert Hex To RGBA Value Using JavaScript - GeeksforGeeks
-
RGBA To HEX Converter - HTMLCSSFreebies
-
Hex To RGB Color Converter
-
Color Code Converter | Color Conversion
-
Html – Convert RGBA To HEX - ITecNote