JavaScript 数组到 PNG?- 客户端

Ker*_*g73 6 javascript arrays png

有没有办法将二维十六进制代码数组转换为 png 图像?

数组看起来像这样(只是大得多)

[
  [
    '#FF0000',
    '#00FF00'
  ],
  [
    '#0000FF',
    '#000000'
  ]
]
Run Code Online (Sandbox Code Playgroud)

从这个数组,图像应该是这样的

在此处输入图片说明

如果该方法不适用于这样的数组,那么它将使用什么类型的数组?

Tim*_* S. 8

如果您想在没有库的情况下呈现 PNG 客户端,您可以使用 HTML5 Canvas。

无论哪种方式,我都建议坚持使用一维数组,并存储图像的尺寸。它使事情变得更容易处理。

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);
Run Code Online (Sandbox Code Playgroud)

或者,如果你不能依赖这样一个相对较新的功能,或者只是觉得这个工作太多,你可以去找汤姆的答案:)