Is it possible to replace a color in a base64-encoded image?

前端 未结 1 1054
情书的邮戳
情书的邮戳 2021-02-01 18:21

Is there any way to take a base 64 string, for example:

.copyIcon {background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQV         


        
相关标签:
1条回答
  • 2021-02-01 18:57

    Here is a little function which takes 3 parameters: data, colorFrom, colorTo (both colors should be supplied in hex)

    function changeColInUri(data,colfrom,colto) {
        // create fake image to calculate height / width
        var img = document.createElement("img");
        img.src = data;
        img.style.visibility = "hidden";
        document.body.appendChild(img);
    
        var canvas = document.createElement("canvas");
        canvas.width = img.offsetWidth;
        canvas.height = img.offsetHeight;
    
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img,0,0);
    
        // remove image
        img.parentNode.removeChild(img);
    
        // do actual color replacement
        var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
        var data = imageData.data;
    
        var rgbfrom = hexToRGB(colfrom);
        var rgbto = hexToRGB(colto);
    
        var r,g,b;
        for(var x = 0, len = data.length; x < len; x+=4) {
            r = data[x];
            g = data[x+1];
            b = data[x+2];
    
            if((r == rgbfrom.r) &&
               (g == rgbfrom.g) &&
               (b == rgbfrom.b)) {
    
                data[x] = rgbto.r;
                data[x+1] = rgbto.g;
                data[x+2] = rgbto.b;
    
            } 
        }
    
        ctx.putImageData(imageData,0,0);
    
        return canvas.toDataURL();
    }
    

    An additional function is required to convert hex colors to RGB (for correct matching)

    function hexToRGB(hexStr) {
        var col = {};
        col.r = parseInt(hexStr.substr(1,2),16);
        col.g = parseInt(hexStr.substr(3,2),16);
        col.b = parseInt(hexStr.substr(5,2),16);
        return col;
    }
    

    Usage would be like so:

    changeColInUri(
        "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVR42mNgQALCi7//J4QZcAFiNOM1hJANBA0h1QC83iHFizDJ/dgww/7/LAQNwKUZbkjDfya8YQZXiCqJagilBmAzhLYGYDNsJBhAMD3gS854NS/6vg+fZgDKvmW19S7PRAAAAABJRU5ErkJggg==",
        "#13A3F7",
        "#ff6400"
    );
    

    It will return a new data:image/png; URI with the swapped colors, here is a working jsfiddle of the end result

    http://jsfiddle.net/V5dU2/

    (tested on Chrome, Firefox and IE10)

    0 讨论(0)
提交回复
热议问题