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