I would like to use threshold filter on base64 string (data:image/png;base64,iVBOR...
) using javaScript like this:
function threshold(base64) { some action whith base64 string... return base64; //base64 is updated by threshold filter }
Is it possible and if it is, how can I do this?
Advertisement
Answer
var base64string = "data:image/png;base64,iVBOR..........", threshold = 180, // 0..255 ctx = document.createElement("canvas").getContext("2d"), image = new Image(); image.onload = function() { var w = ctx.canvas.width = image.width, h = ctx.canvas.height = image.height; ctx.drawImage(image, 0, 0, w, h); // Set image to Canvas context var d = ctx.getImageData(0, 0, w, h); // Get image Data from Canvas context for (var i=0; i<d.data.length; i+=4) { // 4 is for RGBA channels // R=G=B=R>T?255:0 d.data[i] = d.data[i+1] = d.data[i+2] = d.data[i+1] > threshold ? 255 : 0; } ctx.putImageData(d, 0, 0); // Apply threshold conversion document.body.appendChild(ctx.canvas); // Show result }; image.src = base64string;