javascriptdrawimagegetimagedata

Javascript need to output HEX instead of RGB (getImageData, drawImage)


Just to clarify im not very good at javascript and still learning.
I found this pieace of code on the internet, it takes an image and makes it to small span cells to get a pixelated image.
The code works perfect but the only problem I have is i want it to output as a HEX value instead of RGB

image of final output

<body>
    <canvas id="canvas" style="visibility: hidden;"></canvas>
    <div id="final-image" style="line-height: 7px;letter-spacing: -3px;"></div>
    <script>
        const canvas = document.getElementById("canvas");
        const ctx = canvas.getContext("2d");
        const imgUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Radisson_SAS_Scandinavia_voldgrav.JPG/800px-Radisson_SAS_Scandinavia_voldgrav.JPG";
        const img = new Image();
        const imgWidth = 41;

        let html = "";
        img.crossOrigin = "Anonymous";
        img.onload = function() {
            canvas.width = imgWidth;
            canvas.height = (this.height * canvas.width) / this.width;
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            for (let i = 0; i < canvas.height; i++) {
                for (let j = 0; j < canvas.width; j++) {
                    add(ctx.getImageData(j, i, 1, 1).data);
                }
                html += "<br />";
            }
            document.getElementById("final-image").innerHTML = html;
            canvas.parentNode.removeChild(canvas);
        };

        img.src = imgUrl;

        function add(c) {
            html += `<span style="color: rgb(${c[0]}, ${c[1]}, ${c[2]});">&#9632;</span>`;
        }
    </script>
</body>

I have bin looking for it for quite a while now and I must admit I cant fix the solution by myself.
I found this snippet that i though would help me but I could figure it out putting it together.

function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

I've tried to figure out how to get return hex value instead of rgb but dont have the expertise to it


Solution

  • You should be able to construct the hex (which is, of course, also RGB) color value right in the add() function:

    function add(c) {
      const hexpair = v => `${v < 16 ? "0" : ""}${v.toString(16)}`;
      const hex = `#${hexpair(c[0])}${hexpair(c[1])}${hexpair(c[2])}`;
      html += `<span style="color: ${hex};">&#9632;</span>`;
    }
    

    The result should be the same; rgb() is basically a clearer way of doing the same thing that hex color values do.

    edit — a comment points out that since the time I was frozen into a glacier, a standard string method for padding was introduced (.padStart()):

    function add(c) {
      const hexpair = v => `${v.toString(16).padStart(2, "0")}`;
      const hex = `#${hexpair(c[0])}${hexpair(c[1])}${hexpair(c[2])}`;
      html += `<span style="color: ${hex};">&#9632;</span>`;
    }