Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array to PNG? - client side

Is there any way converting a 2d array of hex codes to a png image?

The arrays look like this (only much larger)

[
  [
    '#FF0000',
    '#00FF00'
  ],
  [
    '#0000FF',
    '#000000'
  ]
]

From this array, the image should look like this

enter image description here

If the method doesn't work with arrays like this, what type of array will it work with?

like image 472
Indiana Kernick Avatar asked Feb 09 '15 08:02

Indiana Kernick


2 Answers

If you want to render a PNG client-side, without libraries, you can use the HTML5 Canvas.

Either way, I recommend to stick to a one-dimension array, and store the image’s dimensions. It makes things a lot easier to work with.

var pixels = [ ... ],  // your massive array
    width = 4,         // width in pixels
    height = Math.ceil(pixels.length / width),

    // Create canvas
    canvas = document.createElement('canvas'),
    context = canvas.getContext('2d'),
    imgData = context.createImageData(width, height);

canvas.height = height;
canvas.width = width;

// fill imgData with colors from array
for(var i = 0; i < pixels.length; i++) {
    // Convert pixels[i] to RGB
    // See http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb

    imgData[i] = r;
    imgData[i + 1] = g;
    imgData[i + 2] = b;
    imgData[i + 3] = 255; // Alpha channel
}

// put data to context at (0, 0)
context.putImageData(imgData, 0, 0);

// output image
var img = new Image();
img.src = canvas.toDataURL('image/png');

// add image to body (or whatever you want to do)
document.body.appendChild(img);

Alternatively, if you can’t rely on a relatively new feature like this, or simply find this too much work, you can go for Tom’s answer :)

like image 53
Tim S. Avatar answered Oct 21 '22 05:10

Tim S.


PNGlib looks helpful. You would have to create a loop similar to their example:

var p = new PNGlib(200, 200, 256);

for (var x = 0; x < 2; x++)
    for (var y = 0; y < 2; y++)
        p.buffer[p.index(x, y)] = p.color(/* your colour */);

document.write('<img src="data:image/png;base64,' + p.getBase64() + '">');

It's difficult to give a more specific example with the information that you've provided, but I think that this is what you're after. You would obviously have to change the x and y limits for different arrays.

like image 27
Tom Avatar answered Oct 21 '22 07:10

Tom