Sort Through Hexadecimal Color Codes

I am faced with a challenge of sorting through a vast array of hex colors (over 6500) and I need to eliminate the ones that are excessively dark or overly bright.

Is there a distinguishing feature in the hex codes of dark and bright colors that can help me filter them out? Should I consider converting them into integers for this task..?

Appreciate any guidance you can provide!

Answer №1

This code snippet utilizes a regular expression to extract the brightness value from a given hexadecimal color string, ranging from 0 (black) to 1 (100% white).

function getHexBrightness(hex) {
    var regExp = hex.length < 6 ? /^#(([a-f\d]))(([a-f\d]))(([a-f\d]))$/i : /^#([a-f\d])([a-f\d])([a-f\d])([a-f\d])([a-f\d])([a-f\d])$/i;

    var result = regExp.exec(hex);
    if (result) {
        var r = parseInt("" + result[1] + result[2], 16),
            g = parseInt("" + result[3] + result[4], 16),
            b = parseInt("" + result[5] + result[6], 16),
            max = Math.max(r, g, b),
            min = Math.min(r, g, b),
            l = (max + min) / 2;
        return l / 255;
    }
    return null;
}

// Test
var assert = function (assertion, name) {
    $("<p/>").appendTo(document.body).text(name + (assertion ? ' works' : ' fails'))
}
assert(getHexBrightness('#FFFFFF') == 1, 'Uppercase');
assert(getHexBrightness('#ffffff') == 1, 'Lowercase');
assert(getHexBrightness('#fff') == 1, 'Short');
assert(getHexBrightness('#000') == 0, 'Black');
assert(getHexBrightness('invalid') == null, 'Invalid color');

Check out the live version: http://jsfiddle.net/L7PqT/

Answer №2

Here's a simple and efficient technique you might find useful:

Start by breaking down your Hex color into its individual R/G/B components.

Convert these hex components into decimal, sum them up, and then divide the total by 3 to determine an approximate "brightness" value.

Establish both an upper and lower threshold for the desired brightness level within the standard range of 0 to 255, eliminating any colors that fall outside of these limits.

For example:

#FFBBAA => FF BB AA => ( 255 + 187 + 170 ) / 3 = 204.

If you set your upper threshold at 200 for "brightness," this particular color would be considered too bright. Keep in mind that these thresholds are subjective and can be adjusted based on personal preference.

If you're comfortable working with calculations in Hex directly, you can avoid converting to decimal altogether and perform all calculations using Hex values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

sending an array from Javascript to PHP

Utilizing JavaScript, I have successfully converted data from a file into an array. Now, my goal is to utilize input from a form to search through this array using PHP and present the results in a table. Despite browsing various solutions for similar probl ...

Utilizing Vue Store Methods within an Array or Object

Imagine we have 5 identical buttons. Instead of duplicating them, I decided to make use of v-for. methods: { a() {}, b() {}, ... } Replacing the individual buttons with: <v-btn block color="primary" class="my-1" @click="a">A</v-btn ...

Utilize the split() function to break down a string into separate

I'm facing an issue with splitting a string into an array using a regex that doesn't seem to be working properly. Here is my code: <script type="text/javascript"> function GetURLParameter(sParam) { var sPageURL = window.l ...

Could someone provide me with a breakdown of this code utilizing the .bind() function?

The code snippet above is from the jQuery source code and it deals with event handling. It defines an array of events, such as click, focus, blur, etc., and then adds each event to the jQuery prototype using a forEach loop. var events = ['click', ...

After making changes to the variables in my forEach loop, they revert back to their initial values

I have been attempting to create a query to retrieve all earnings and withdrawal amounts and then sum them up. However, I have encountered an issue where, after the forEach loop finishes and exits, the updated values stored in a variable revert back to t ...

Issue with date range filter functionality not functioning as expected

Struggling to get the date range filter to function properly. Selecting a date triggers it, but nothing is being added to the var filter. I've spent hours trying to solve this issue with no progress. html <div class="form-group"> <input ...

Performing a function when the ondrop event of a <li> element is triggered

Is there a way to trigger a code-behind click function on the ondrop event of an <li> element? Additionally, I would like to know if it's possible to force a postback on the onclick event. Any ideas on how to achieve this? Just to clarify, thi ...

Encountered a TypeError while attempting to log in as a client

Currently, I am embarking on the initial stages of developing a small Circuit Bot using Node.js. Here is the progress I have made so far: const Circuit = require('../node_modules/circuit-sdk/circuit.js'); //Importing Circuit Library var config ...

What is the best way to define Bootstrap 5's CSS variables with the :root selector?

I am working with a Bootstrap 5 application that utilizes various web components, all styled with Bootstrap 5. I am looking to dynamically customize the theme within the parent component that integrates these web components. The basic structure of my setup ...

Automate the process of modifying specific data in tables through Javascript

I've been attempting to replicate the appearance of a stock-exchange board, but I'm encountering difficulties in updating text automatically without interrupting another. My attempts so far: var textPositive = ["2.0%", "1.7%" ...

How to Show an Image in a Search Bar Using HTML

As I put the finishing touches on this table, I decided to add a search function to it. However, I encountered an issue with the search bar design. I wanted to incorporate a search icon png file as the background image, similar to the example showcased on ...

The 'innerText' property is not present in the 'Element' type. (2339)

Recently, I've been working with javaScript and I encountered some issues while writing a function. Strangely, I kept receiving error messages that I couldn't quite understand. Initially, there was a problem where every time I tried to create a j ...

Transitioning from a fixed position to absolute in CSS3

Sticky Logo Element In my project, I implemented a logo element that is positioned absolutely within the document. As the user scrolls, the logo sticks to the top of the window with a fixed position (you can view an example here: https://jsfiddle.net/swzb ...

Section with relative positioning has taken an unexpected position

I'm facing a rather basic issue with positioning a relative div on my webpage. My layout consists of an absolute header that is 100vh tall, containing a headline and caption. Below the header, I have two section elements, both set to a relative posit ...

How can a JavaScript function communicate with a code behind method?

Currently, I am trying to implement a JavaScript function for an HTML img click event on an aspx page. Additionally, there is a server method in the code behind page that I need to call from the JavaScript function without any parameters whenever the user ...

Links in words not redirecting to asp.net documents

I have a collection of Word files that require hyperlinks. These hyperlinks lead to an htm file with an anchor, however the htm file is not accessible directly via a URL for security purposes. Instead, it links to an ashx handler file which fetches the f ...

Issue with visibility of Bootstrap modal title

The title in the modal isn't visible. Even when I highlight it with a mouse, it still doesn't show up. I attempted to add modal-content color: #000, but unfortunately, it had no effect. As of 01/11/16 1:28PM CST, none of the responses and answe ...

Limiting the number of characters in a textarea using React with TypeScript

Having encountered two issues, I've developed a textarea component that not only allows users to input text but also keeps track of the number of characters they have typed. First Issue: I'm attempting to check if the length of the current input ...

Issue encountered with react-toolbox 2.0-beta.6's ThemeProvider not functioning as expected

I have been attempting to modify the color-primary and color-accent variables in react-toolbox using react-toolbox-themr, but without success. I have created a simple git repository to showcase this issue. Below is my react-toolbox-themr.config.json: { ...

Collapsible List Group Button Utilizing Bootstrap Remains Expanded

Looking for some guidance here. I am just starting out with Bootstrap and trying to learn from their website, but I'm having trouble figuring out how to make something collapsed. I found collapse.js, jquery.min.js, bootstrap.min.js, and transition.js ...