Html5 canvas element color depth change

I was wondering if there is a way to change the color depth of the image in the HTML5 canvas element, since the color of each pixel in the image will be β€œrounded” to the nearest equivalent at a lower color depth, for example. Thanks.

+4
source share
3 answers

Yes, it can be done, and it is not too difficult. See My answer here: How to use a gradient map to tint an HTML5 canvas with an image on the canvas.

As with toning, just all you have to do is iterate over each pixel and change the RGB values ​​to a smaller one (steps 8 or 16 instead of steps 1)

So, in 8 steps you can do:

redValue = redValue - (redValue % 32) // 155 would become 128, etc 

Which should work, but you should check for edge cases.

Example:

http://jsfiddle.net/gbBz7/

+9
source

I do not think there is a built-in setting for this. But you should be able to reduce the value of each pixel channel to a more limited set of values. Sort of:

 var ctx, width, height; var factor = 8; var pixels = ctx.getImageData(0, 0, width, height).data; function reduce(val) { return Math.round(val/factor)*factor; } for(var i = 0, l = pixels.length; i < l; i+=4) { pixels[i] = reduce(pixels[i]); pixels[i+1] = reduce(pixels[i+1]); pixels[i+2] = reduce(pixels[i+2]); } ctx.putImageData(pixels, 0, 0) 
+3
source

You can iterate over each byte of each color with getImageData so that you can apply some mathematical functions to it, for example. represent 8-bit colors : http://jsfiddle.net/pimvdb/eGjak/191/ .

 var imgdata = ctx.getImageData(0, 0, 400, 400); // get data var data = imgdata.data; // bytes // 8-bit: rrr ggg bb for(var i = 0; i < data.length; i += 4) { data[i] = nearest(data[i], 8); // set value to nearest of 8 possibilities data[i + 1] = nearest(data[i + 1], 8); data[i + 2] = nearest(data[i + 2], 4); } ctx.putImageData(imgdata, 0, 0); // put image data to canvas function nearest(x, a) { // will round down to nearest of a possibilities // in the range 0 <= x <= 255 return Math.floor(x / (255 / a)) * (255 / a); } 
+1
source

All Articles