1
\$\begingroup\$

I want to improve the code, in which you can enter a grey bitmap and it will return you a colored one.

function ChangeBaseGrey(bitmap, color)
{
var canvas = document.getElementById("imagesColored");
var ctx = canvas.getContext("2d");
var dataBitmap = bitmap.data;

var r0 = (color >> 16) & 0xff,
    g0 = (color >> 8) & 0xff,
    b0 = color & 0xff;

for(var c = 0; c < dataBitmap.length; c += 4)
{
    var r1 = dataBitmap[c],
        g1 = dataBitmap[c + 1],
        b1 = dataBitmap[c + 2];

    if(dataBitmap[c + 3] > 0 && (r1 == g1 && r1 == b1 && g1 == b1))
    {
        var co = color;
        dataBitmap[c] = colorRGBBound(r0 * (r1 / 255));
        dataBitmap[c + 1] = colorRGBBound(g0 * (g1 / 255));
        dataBitmap[c + 2] = colorRGBBound(b0 * (b1 / 255));
    }
}

ctx.putImageData(bitmap, 0, 0);

var finalImage = new Image();
finalImage.src = canvas.toDataURL("image/png");

return finalImage; // Colored Image Output
}
\$\endgroup\$
1
\$\begingroup\$

From a once over:

  • Your indenting is off, this might be a copy paste problem into the question, consider using jsbeautify
  • You never use var co = color;, throw it away
  • (r1 == g1 && r1 == b1 && g1 == b1) consider that if r1 = g1 and r1 = b1, then g1 must be equal to b1 so you can use the simpler (r1 == g1 && r1 == b1)
  • I am not sure why you update the bitmap AND create a new image, I would do only 1 of these for extra speeds
  • r0,g0,b0 and r1,g1,b1 are not the most intuitive variable names..
  • Consider caching the values of colorRGBBound(r0 * (r1 / 255)); , there are only 255 possibilities for the value of r1 and you can use the same cache for r1,g1 and b1
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.