Search code examples
javascriptarrayspng

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?


Solution

  • 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 :)