有没有办法将二维十六进制代码数组转换为 png 图像?
数组看起来像这样(只是更大)
[
[
'#FF0000',
'#00FF00'
],
[
'#0000FF',
'#000000'
]
]
从这个数组中,图像应该是这样的
如果该方法不适用于这样的数组,它将适用于哪种类型的数组?
最佳答案
如果您想在没有库的情况下呈现 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);
或者,如果您不能依赖这样一个相对较新的功能,或者只是觉得这工作量太大,您可以寻求 Tom 的答案 :)
关于JavaScript数组到PNG? - 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28405619/