What is the process of creating a color range in Java?

I am looking for a way to input a 6-digit RGB-hex number and then be able to click on a button that will display the corresponding color name. Unfortunately, I have not been able to find a color library in Java that can provide me with the names of arbitrary colors.

My approach: I came across a JavaScript library called "ntc js lib" which assigns names to colors based on their hex values. I tried to replicate this functionality in Java by creating a hash map where each key-value pair represents a hex color value and its corresponding name, like so:

sColorNameMap.put("B43332", "Well Read");

The code works fine if I input a key that matches one of the values stored in the hash map. For example, when I enter the value B43332, it correctly returns the name "Well Read".

My issue: However, I am facing difficulties when entering a value that does not exactly match any of the keys in the hash map. In such cases, I am unable to retrieve the color name.

What I require: I am in need of a function that can return the name of the closest matching color. I have attempted to understand how the ntc library achieves this but have been unsuccessful in doing so.

For instance, the value B23634 is not predefined in the ntc js lib, yet it resolves to the name "Well Read," as depicted in this image: https://i.sstatic.net/1SB6S.png Any guidance or assistance in implementing a function that can determine the closest matching color based on a given 6-digit hex value would be greatly appreciated.

Answer №1

When determining the nearest color match based on proximity in the RGB space, you can utilize a method like the following:

(refer to this source for guidance on computing this distance)

public static void main(String[] args) {

    Map<String, String> sColorNameMap = new HashMap<>();

    String rgbCode = "B23634";

    String colorName;
    if (sColorNameMap.containsKey(rgbCode)) {
        colorName = sColorNameMap.get(rgbCode);
    } else {
        colorName = nearestColor(rgbCode, sColorNameMap);
    }

    System.out.println("colorName = " + colorName);

}

private static String nearestColor(String code, Map<String, String> sColorNameMap) {

    int[] rgb = getRgb(code);

    double nearestDistance = Double.MAX_VALUE;
    String nearestNamedColorCode = null;

    for (String namedColorCode : sColorNameMap.keySet()) {
        int[] namedColorRgb = getRgb(namedColorCode);
        double distance = calculateDistance(rgb, namedColorRgb);
        if (distance < nearestDistance) {
            nearestDistance = distance;
            nearestNamedColorCode = namedColorCode;
        }
    }

    return sColorNameMap.get(nearestNamedColorCode);

}

private static int[] getRgb(String code) {

    int r = Integer.parseInt(code.substring(0, 2), 16);
    int g = Integer.parseInt(code.substring(2, 4), 16);
    int b = Integer.parseInt(code.substring(4, 6), 16);

    return new int[]{r, g, b};

}

private static double calculateDistance(int[] rgb1, int[] rgb2) {

    double sum = 0.0;
    for (int i = 0; i < 3; i++) {
        sum += Math.pow(rgb2[i] - rgb1[i], 2);
    }
    return Math.sqrt(sum);

}

If another criteria is used for finding the nearest matching color, adjustments can be made within the calculateDistance() method.

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

When trying to create a MongoStore object, an error occurred because the property 'create' was not defined

I have exhausted all possible solutions I could find, but the issue remains unresolved. The error message is as follows: C:\Users\...............\server.js:35 store: MongoStore.create({ ^ TypeError: Cannot read property &a ...

Incorporating Mongoose Schema structures into my NextJS webpage

I am new to NextJS and seeking assistance with an issue I am facing. I have defined 2 Mongoose schemas and using one on my page without any problems. However, when I try to import the second schema, my page fails to render and throws an error. Regardless ...

React i18next provides a fallback language in case the specified language is not

In my React app, I have implemented i18next for translating files, using the following approach: i18next.js (original) import i18next from 'i18next'; import XHR from 'i18next-xhr-backend'; import detector from 'i18next-browser-lan ...

Ways to reset input fields following form submission

I've been trying to figure out how to clear the input fields once the form is submitted, but for some reason, the input data remains there even after each submission. I'm using ajax jquery form. Any ideas on how to resolve this issue? Thank you ...

Tips for updating a JSONObject within an array using keys from two separate JSON arrays

I am dealing with two JSON arrays named http and websocketjsonArray. A condition that I need to follow inside a nested for loop is when the scripcode and userid are the same in both arrays, then update the data from websocketjsonarray into http array. Plea ...

Automatic Clicks in the Chrome Console

I've come across a website that requires me to click on multiple elements scattered throughout the page Here is the code for one of the elements: <span class="icon icon-arrow-2"></span> Is there a way to provide me with the console comm ...

What is the reason for the error that Express-handlebars is showing, stating that the engine

I recently added express-handlebars to my project and attempted the following setup: const express = require("express"); const exphbs = require('express-handlebars'); const app = express(); app.engine('.hbs', engine({defaultL ...

Learning how to use Express.js to post and showcase comments in an HTML page with the help of Sqlite and Mustache templates

I am facing a persistent issue while trying to post new comments to the HTML in my forum app. Despite receiving various suggestions, I have been struggling to find a solution for quite some time now. Within the comments table, each comment includes attrib ...

When using Rails to render a JSON page remotely, the JavaScript AJAX handler fails to capture the response

My goal is to have a form that can post remotely and then receive JSON data back for my JavaScript to process. Below is the code I am using: <%= form_tag '/admin/order_lookup', remote: true, authenticity_token: true, id: "order-lookup-submit" ...

does not dynamically update hasAttribute

I am encountering an issue with jQuery Validator on my form. Despite being checked or unchecked, the checked attribute does not change on my validator when I submit the form. Below is the snippet of HTML: <div class="col-sm-10 col-sm-offset-1"> ...

Ways to acquire ttf files from a third-party domain without encountering CORS issues

I am attempting to obtain a .ttf file from an external website for use in my web application. However, when I try the following code: @font-face { font-family: 'font'; src: url('http://xxx.xyz/resources/tipografias/font.ttf') forma ...

Problem with AngularJS Multiselect checkbox dropdown configuration

In my application, I have a pop-up that includes a multi-select dropdown menu. Here is the code for the Multi-Select Dropdown: <select name="edit_tags" class="form-control" id="advisor_article_tagsx" multiple="" required ng-model="article_selected ...

Express/axios fails to properly configure cookies and headers for response delivery

I am facing a complex issue with my project that involves two APIs. One API serves as the front-end of the application, while the other is for the back-end. The process simply entails sending requests from the front-end API to the back-end API. The front- ...

What is the best way to update my logo and incorporate a colored border at the bottom of my fixed header while the user is scrolling down?

After spending countless hours researching online, I've been struggling to implement header effects on scroll without using JavaScript. My goal is to achieve a simple effect where the header reduces in height, the logo changes, and a colored border is ...

Conceal a div until reaching the end of the webpage by scrolling

Currently, I am working on a web page inspired by music release pages (check out an example here). My goal is to have certain hidden divs at the bottom of the page only reveal themselves once the user has scrolled all the way down, with a delay of a few se ...

Date Boxes in a Tangled Web

Looking to showcase multiple dates on a screen, I'm encountering an issue where clicking on a date button opens a datepicker. If the user clicks out of the box, the datepicker closes properly. However, when another datepicker button is clicked, instea ...

Axios encounters CORS issues, while fetch operates smoothly

After going through various questions on CORS errors to no avail, I am facing a dilemma in my NuxtJS client application. Whenever I try to make a simple POST request using axios, I encounter CORS issues. However, when I switch to using the fetch API, every ...

"Why does the form.submit() function fail in IE9 when the form is in an iframe and the user is coming from Gmail

I have recently developed a function within my CodeIgniter framework that allows me to send emails with a backlink to my site. The link directs users to a page on my website that includes an iframe. Within this iframe, I have implemented a file input form ...

Having trouble accessing an injector service within the promise of a dynamically loaded JavaScript function that has been assigned to a global variable

Query I am facing an issue while trying to integrate PayPal with Angular. I am encountering difficulties when attempting to call an injected service inside a function of the promise returned. Any assistance in resolving this would be greatly appreciated. ...

Expanding Gridview Width within a Container in ASP.Net: A Step-by-Step Guide

https://i.stack.imgur.com/ZaJE7.jpg After viewing the image above, I am facing a challenge with stretching and fixing a gridview to contain the entire div where it is placed. The issue arises when the gridview adjusts automatically based on the content&ap ...