How do i reconstruct the image from an array of data in javascript. And display it on my page.
the data is not hex or binary but a color value [0-255] black and white, so 8 bits image.
Could some one give me show direction on how to rebuild the image from such raster data. I refer native javascript image object.
here is a simple snippet of the data.
IMAGE
{"data":[[9,6,7,7,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,9,9,10,9,9,10,9,10,10,10,10,9,9,9,9,9,10,9,9,10,9,10,9,9,9,10,9,9,10,9,9,10,9,9,10,9,9,10,10,10,9,10,9,9,10,10,10,10,10,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,10,10,10,11,10,10,11,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,10,10,11,11,11,11,11,10,11,10,11,11,10,11,11,11,11,11,11,11,12,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,11,11,12,12,11,12,11,11,11,12,11,11,12,12,12,11,11,12,12,12,11,12,12,12,12,12,12,
Each of them represent each pixel.
Thanks
The data you're providing (albeit incomplete) is extremely similar to the format given by .getImageData()
. So that is what I've used to create a simple solution.
function dataToBase64(colors, width, height){
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
color;
//setup canvas
canvas.width = width,
canvas.height = height;
//grab data
var data = ctx.getImageData(0, 0, width, height),
_data = data.data; //simple speed optimization
//place data
for(var i = 0, l = _data.length; i < l; i+=4){
color = colors[i/4];
_data[i] = color,
_data[i+1] = color,
_data[i+2] = color,
_data[i+3] = 255;
}
ctx.putImageData(data, 0, 0);
//return base64 string
return canvas.toDataURL();
}
Note that this function returns a Base64 string, which you then need to do something with. I've provided a fiddle to show you how to use the function.