Convert code blobs of html colors to greyscale
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

Id like to make a javascript solution so I can quickly copy in a bunch of code with html colors in it and have the js find and replace all of the implied colors with their greyscale equivalent. using method 2 from this article https://tannerhelland.com/2011/10/01/grayscale-image-algorithm-vb6.html lets have a simple html input where the user can copy a bunch of code from vs like this https://gist.github.com/curtis-arch/e327a5d6f0e3a8e999f1b7d1c79f6103 and it will parse the code and only touch the html colors. for each color it finds it will process it through the color conversion algo mentioned above. The output should be the exact same code that was input but with the new values. I'm picturing something like this https://codebeautify.org/jsviewer where you put your code on left and you get the output on right.

Tags
javascript

Crowdsource coding tasks.

1 Solution


grayscale.js

var fs = require("fs");

function convertToGrayscale(filename) {
    fs.readFile(filename, "utf8", function (err, data) {
    if (err) throw err;

    var result = data.replace(/(#)(.*?)( ?!default;)/g,
        function (match, p1, p2, p3) {
            var color = p2.trim();
            var grayScale = getGrayScaleLuma(color);
            return p1 + grayScale + p3;
        });

    fs.writeFile("output-" + filename, result, "utf8", function (err) {
        if (err) throw err;
        console.log("The file has been saved!");
    });
});
}

function getGrayScaleLuma(color) {
var r, g, b;
if (color.length === 4) {
    r = parseInt(color[1] + color[1], 16);
    g = parseInt(color[2] + color[2], 16);
    b = parseInt(color[3] + color[3], 16);
} else {
    r = parseInt(color.substring(1, 3), 16);
    g = parseInt(color.substring(3, 5), 16);
    b = parseInt(color.substring(5, 7), 16);
}

var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
var grayHex = Math.round(gray).toString(16);
if (grayHex.length === 1) grayHex = "0" + grayHex;
return grayHex + grayHex + grayHex;
}

module.exports = {
    convertToGrayscale: convertToGrayscale,
    getGrayScaleLuma: getGrayScaleLuma,
};

index.js

const convertToGrayscale = require("./grayscale").convertToGrayscale;

convertToGrayscale("code.txt");