I am trying to color the black pixels of a black-and-white image on a canvas.
The naive code I'm using is:
function color_text(canvas, r, g, b, w, h) {
var ctx = canvas.getContext('2d');
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var pixels = imageData.data;
for (var x = 0; x < w; x++) {
for (var y = 0; y < h; y++) {
var redIndex = ((y - 1) * (canvas.width * 4)) + ((x - 1) * 4);
var greenIndex = redIndex + 1;
var blueIndex = redIndex + 2;
var alphaIndex = redIndex + 3;
if ((pixels[redIndex] < 240) && (pixels[greenIndex] < 240) && (pixels[blueIndex] < 240)) {
pixels[redIndex] = r;
pixels[greenIndex] = g;
pixels[blueIndex] = b;
}
}
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.putImageData(imageData, 0, 0);
}
I use < 240 as a detector for non-white pixels instead of exactly 255 because these are scanned in pieces of hand-drawn calligraphy, so a fudge factor is needed. Applying this algorithm to an image that is scaled down by canvas's native drawImage() produces results that look as good as the black-and-white image.
However, canvas's native drawImage() leaves much to be desired, so instead, I scaled down the image with a slightly-modified version of the code provided in this answer. The black and white image produced by this code is beautiful, much better than canvas's native method. However, when I color the image with the above function, it looks awful again.
A complete jsfiddle is here: http://jsfiddle.net/q9sd9w1k/
Any ideas on how I can color the high-quality version effectively?
Thanks.