Advertisement


Change the color of an image in a website


Question

I have this image in my website, is a png:

enter image description here

I want to know if there is any way with HTML5, javascript or css to change the color of the image. Or at least make the image change to white (invert color black to white, not the transparency).

2012/11/19
1
3
11/19/2012 1:03:00 AM

Accepted Answer

I'm not sure this belongs on GD, but...

It can be done using HTML5's CANVAS element, here's a super quick & dirty:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript">
    window.onload = function(){
        var imageObj = new Image();
        imageObj.onload = function(){ alterImage(this); }
        imageObj.src = document.getElementById( "origImg" ).src;
    }

    function alterImage(imageObj){
        var canvas = document.getElementById("myCanvas");
        var ctx= canvas.getContext("2d");

        ctx.drawImage(imageObj, 0, 0);
        var id= ctx.getImageData(0, 0, canvas.width, canvas.height);

        // Iterate over data.  Data is RGBA matrix so go by +=4 to get to next pixel data.
        for (var i = 0; i < id.data.length; i += 4) {
            // Check if RGB == 0 (black)
            if ( id.data[i] + id.data[i+1] + id.data[i+2] == 0 )
                id.data[i] = 255; //change R bit to 255.
                // change G & B bits to 255 also if you want white.
        }

        // redraw your altered data on the canvas.
        ctx.putImageData(id, 0, 0);
    }
    </script>
  </head>
  <body>
    <img id="origImg" src="test.png" alt="Original image">
    <canvas id="myCanvas" width="250" height="100"></canvas>
  </body>
</html>

BUT YOU DON'T WANT TO DO THIS!

Problems:

  1. getImageData requires privilege elevation unless the source images are hosted on the same domain as the script. You can't use any hosting services unless you want to bother users with priv-escalation prompts.
  2. If your user has Javascript disabled, or an older browser that doesn't support HTML5, it won't work.
  3. HTML5 is still in draft so the canvas implementation could change.
  4. You're asking your browsers to do image processing for you every time the image is loaded. If you're only using a few basic colors, you're better off doing your own processing and determining which image to serve at response time instead of expecting them to process. (And, if you care, from a "green" standpoint, you end up asking users to reproduce the exact same "Color X" version countless times using countless CPU cycles which uses more power and yada yada yada.)

You can save CPU cycles for you and your users by just creating the colors you need server-side (there are scripts that can do this for you) and serving them the colors they need. You only want to use canvas for this if you have no other choice (e.g. the user is determining the color on the fly).

Similar questions have also been asked on SO a few times:

2017/05/23
2
5/23/2017 12:40:00 PM